Best time to buy and stock Stock II
Say you have an array for whichITh element is the price of a given stock on dayI.
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 ).
Algorithm ideas:
Calculate the difference value of each increment interval. Sum.
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 if(prices == null || prices.length < 2) return 0; 4 int pre = 0, post = 1,length = prices.length; 5 int buy = 0,profit = 0; 6 for(int i = 0; i < prices.length; i++,pre = i - 1, post = i + 1){ 7 if(post < length && prices[pre] >= prices[i] && prices[post] > prices[i]){ 8 buy = prices[i]; 9 }10 if( prices[i] > prices[pre] && (post != length ? prices[i] >= prices[post] : true) ){11 profit += prices[i] - buy;12 }13 }14 return profit;15 }16 }