LeetCode --- Best Time to Buy and Sell Stock II
4422 ワード
タイトルリンク
コードを添付:
コードを添付:
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 unsigned int len = prices.size(); 5 if (len == 0) return 0; 6 // ans: holds the total profit that has been earned
7 int ans = 0; 8 for (int i = 0; i < len; ) { 9 // buy: holds price of the ith day where 10 // i is the maximum index satisfing 11 // prices[i-1] > prices[i] and prices[i] <= prices[i+1]
12 int buy = prices[i++]; 13 while (i < len && prices[i] < buy) { 14 buy = prices[i++]; 15 } 16 if (i >= len) return ans; 17 // sell: holds price of the ith day where 18 // i is the maximum index satisfing 19 // prices[i-1] < prices[i] and prices[i] >= prices[i+1]
20 int sell = prices[i++]; 21 while (i < len && prices[i] > sell) { 22 sell = prices[i++]; 23 } 24 ans += (sell - buy); 25 } 26
27 return ans; 28 } 29 };