The idea is to have two loop variables, and another to record max.
if lp2 < lp1, update lp1; otherwise keep update max if array[lp2]-array[lp1] > max.
public class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int b = 0;
int s = 0;
while(s < prices.length){
if(prices[s] < prices[b]){
b = s;
s++;
continue;
}
if(prices[s] > prices[b]){
if(prices[s] - prices[b] > maxProfit){
maxProfit = prices[s] - prices[b];
}
}
s++;
}
return maxProfit;
}
}
没有评论:
发表评论