https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
解法1:贪心
与121题不同,这题可以多次买卖没有对交易次数限制,所以我们可以采用贪心策略,只要赚钱,我们就将股票出售
buyday记录购买日期,i遍历数组,若第i天大于buyday时的价格就让结果值加上这个利润,且更新buyday=i
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: int maxProfit(vector<int>& prices) { int buyday=0; int res=0; int n=prices.size(); for(int i=0;i<n;i++) { if(prices[i]<prices[buyday]) buyday=i; else if(prices[i]>prices[buyday]) { res+=prices[i]-prices[buyday]; buyday=i; } } return res; } };
|