public class Solution {
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
if (prices.length < 1)
return 0;
int[] lowest = new int[prices.length];
int[] highest = new int[prices.length];
int min = prices[0];
for (int i=0; i<prices.length; i++) {
min = Math.min(min, prices[i]);
lowest[i] = min;
}
int max = prices[prices.length-1];
for (int i=prices.length-1; i>=0; i--) {
max = Math.max(max, prices[i]);
highest[i] = max;
}
max = 0;
for (int i=0; i<lowest.length; i++)
max = Math.max(max, highest[i]-lowest[i]);
return max;
}
}
第一题很简单,时间复杂度为 O(N)