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 your transactions as you like (ie, buy one and every one share of the stock multiple times ). however, you may not engage in multiple transactions at the same time (ie, you must wait the stock before you buy again ).
1: Pay attention to special cases; 2: Find adjacent concave points and convex points of the array; 3: The difference between the two is the current maximum value; 4: Pay attention to the boundary when searching for convex and concave values
int maxProfit(vector<int> &prices) { if(prices.size() <= 1) { return 0; } int maxValue = 0; int start = 0; int end = 0; int size = (int)prices.size(); while(start < size) { while(start < size - 1 && prices[start] >= prices[start + 1]) { start++; } end = start + 1; while(end < size - 1 && prices[end] <= prices[end + 1]) { end++; } if(end == size) { break; } else { maxValue += prices[end] - prices[start]; } start = end + 1; } return maxValue; }