Thought:
Just Keep track of the min price and the local max profit.
Code:
public class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
if(prices.length == 0) return profit;
int min = prices[0];
for(int i = 1; i < prices.length; i++) {
if( prices[i] - min > profit){
profit = prices[i] - min;
}else if( prices[i] < min) {
min = prices[i];
}
}
return profit;
}
}
No comments:
Post a Comment