-
分发饼干: https://leetcode-cn.com/problems/assign-cookies/
class Solution { public: int findContentChildren(vector<int>& g, vector<int>& s) { sort(g.begin(), g.end()); sort(s.begin(), s.end()); int numOfChildren = g.size(), numOfCookies = s.size(); int count = 0; for (int i = 0, j = 0; i < numOfChildren && j < numOfCookies; i++, j++) { while (j < numOfCookies && g[i] > s[j]) { j++; } if (j < numOfCookies) { count++; } } return count; } };
-
最大子数组和: https://leetcode-cn.com/problems/maximum-subarray/
class Solution { public: int maxSubArray(vector<int>& nums) { int pre = 0, maxAns = nums[0]; for (const auto &x: nums) { pre = max(pre + x, x); maxAns = max(maxAns, pre); } return maxAns; } };
-
买卖股票的最佳时机: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
class Solution { public: int maxProfit(vector<int>& prices) { int inf = 1e9; int minprice = inf, maxprofit = 0; for (int price: prices) { maxprofit = max(maxprofit, price - minprice); minprice = min(price, minprice); } return maxprofit; } };
-
买卖股票的最佳时机 II: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
class Solution { public: int maxProfit(vector<int>& prices) { int ans = 0; int n = prices.size(); for (int i = 1; i < n; ++i) { ans += max(0, prices[i] - prices[i - 1]); } return ans; } };
【数据结构c++】贪心思想(十)
最新推荐文章于 2022-11-18 16:46:29 发布