122. Best Time to Buy and Sell Stock II

class Solution { public: int maxProfit(vector<int>& prices) { if (prices.empty()) return 0; // the problem is like finding all the increasing subsequences in the prices vector int profit = 0; size_t start = 0; while(true){ while(prices[start+1] < prices[start] && start < prices.size()) start++; size_t end = start+1; while(prices[end+1] > prices[end] && end < prices.size()) end++; // if the subsequence is valid we append if (start < prices.size() && end < prices.size()){ profit += prices[end] - prices[start]; start = end; } else return profit; } } };

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.