贪心策略

[Algo] 贪心策略

1. 最大数

// 1. 最大数
// https://leetcode.cn/problems/largest-number/
string largestNumber(vector<int>& nums) {
    int len = nums.size();
    vector<string> nums_str(len);
    bool all_zero = true;
    for (int i = 0; i < nums.size(); i++) {
        nums_str[i] = to_string(nums[i]);
        if (nums[i] != 0) all_zero = false;
    }
    if (all_zero) return "0";
    sort(nums_str.begin(), nums_str.end(), [](const string &a, const string &b){
        return a + b > b + a;
    });
    string ans;
    for (int i = 0; i < nums.size(); i++) ans += nums_str[i];
    return ans;
}

2. 两地调度

// 2. 两地调度
// https://leetcode.cn/problems/two-city-scheduling/
int twoCitySchedCost(vector<vector<int>>& costs) {
    int num = costs.size();
    sort(costs.begin(), costs.end(), [](const vector<int> &a, const vector<int> &b){
        return a[1] - a[0] < b[1] - b[0];
    });
    int ans = 0;
    for (int i = 0; i < num / 2; i++) ans += costs[i][1];
    for (int i = num / 2; i < num; i++) ans += costs[i][0];
    return ans;
}

3. 吃掉n个橘子的最少天数

// 3. 吃掉n个橘子的最少天数
// https://leetcode.cn/problems/minimum-number-of-days-to-eat-n-oranges/
unordered_map<int, int> dp;
int minDays(int n) {
    if (n <= 1) return n;
    if (dp.count(n) != 0) return dp[n];
    int ans = min(n % 2 + 1 + minDays(n / 2), n % 3 + 1 + minDays(n / 3));
    dp[n] = ans;
    return ans;
}

4. 课程表 III

// 4. 课程表 III
// https://leetcode.cn/problems/course-schedule-iii/
int scheduleCourse(vector<vector<int>>& courses) {
    sort(courses.begin(), courses.end(), [](const vector<int> &a, const vector<int> &b) {
        return a[1] < b[1];
    });
    priority_queue<int, vector<int>, less<int>> max_heap;
    int time_stamp = 0;
    for (auto &course : courses) {
        if (time_stamp + course[0] <= course[1]) {
            time_stamp += course[0];
            max_heap.push(course[0]);
        } else if (!max_heap.empty() && max_heap.top() > course[0]) {
            time_stamp += course[0] - max_heap.top();
            max_heap.pop();
            max_heap.push(course[0]);
        }
    }
    return max_heap.size();
}
posted @ 2025-06-14 09:01  yaoguyuan  阅读(6)  评论(0)    收藏  举报