Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
这道题就是找到最多的递增子序列个数,然后把利润加总。
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (prices.size() == 0) 7 return 0; 8 9 int start = prices[0]; 10 int profit = 0; 11 for(int i = 1; i < prices.size(); i++) 12 { 13 if (prices[i] >= prices[i-1]) 14 continue; 15 16 profit += prices[i-1] - start; 17 18 start = prices[i]; 19 } 20 21 profit += prices[prices.size()-1] - start; 22 23 return profit; 24 } 25 };