自己的题解:动态规划
class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0) return 0;
int min = prices[0];
int ans = 0;
for (int i = 1; i < prices.length; i++) {
if(min>=prices[i]) {
min = prices[i];
continue;
}
ans = Math.max(ans, prices[i]-min);
}
return ans;
}
}
学习了一下k神的题解:
class Solution {
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE, ans = 0;
for (int i =0; i < prices.length; i++) {
min = Math.min(min, prices[i]);
ans = Math.max(ans, prices[i]-min);
}
return ans;
}
}