Question
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).
Solution
The key to this problem is to only consider local minimizer point and local maximizer point. And then add up sums. In this way, we avoid processing situation that transactions happen on one day.
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 if (prices == null || prices.length < 2) 4 return 0; 5 int result = 0, localMin = prices[0], localMax = prices[0], i = 0, length = prices.length; 6 while (i < length) { 7 // To find local minimizer point 8 while (i < length - 1 && prices[i + 1] < prices[i]) 9 i++; 10 localMin = prices[i]; 11 12 // To find local maximizer point 13 i++; 14 if (i == length) { 15 localMax = prices[length - 1]; 16 } else { 17 while (i < length - 1 && prices[i + 1] > prices[i]) 18 i++; 19 if (i < length - 1) 20 localMax = prices[i]; 21 else if (i == length - 1) 22 localMax = prices[length - 1]; 23 } 24 result += (localMax - localMin); 25 } 26 return result; 27 } 28 }