The idea is to update all positive case… whenever lp2 value smaller than lp1 value, update max and being index… the comparison between lp2 - 1 and begin is NOT necessary since the algorithm guarantees b value <= lp2 - 1 value. otherwise begin index should already be updated to lp2 - 1.
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length < 2){
return 0;
}
int begin = 0;
int end = begin + 1;
int sum = 0;
int preEnd = end - 1;
while(end < prices.length){
if(prices[end] < prices[preEnd]){
sum += (prices[preEnd] - prices[begin] > 0 ? prices[preEnd] - prices[begin] : 0);
begin = end;
}
preEnd = end;
end++;
}
if(begin < preEnd){
sum += prices[preEnd] - prices[begin];
}
return sum;
}
}
没有评论:
发表评论