自己写的稍微有点复杂了,其实完全可以不用数组。用一个cost 和 profit 就可以了。但是值得高兴的是,自己的思路跟上了大佬的思路,想到了动态规划。
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) return 0;
int len = prices.length;
int[] dp = new int[len];
dp[0] = 0;
int min = prices[0];
for(int i = 1;i < len;i++){
if(prices[i] <= min) {
min = Math.min(min, prices[i]);
dp[i] = dp[i - 1];
} else {
dp[i] = Math.max(dp[i - 1], prices[i] - min);
}
}
return dp[len - 1];
}
简洁的代码来源:
https://leetcode-cn.com/problems/gu-piao-de-zui-da-li-run-lcof/solution/mian-shi-ti-63-gu-piao-de-zui-da-li-run-dong-tai-2/
public int maxProfit(int[] prices) {
int cost = Integer.MAX_VALUE, profit = 0;
for(int price : prices) {
cost = Math.min(cost, price);
profit = Math.max(profit, price - cost);
}
return profit;
}