题目描述
方法1:记录最低价格
只需要遍历价格数组一遍,记录历史最低点,然后在每一天考虑这么一个问题:如果我是在历史最低点买进的,那么我今天卖出能赚多少钱?当考虑完所有天数之时,我们就得到了最好的答案
class Solution {
public int maxProfit(int[] prices) {
int min = prices[0];
int maxProfit = 0;//当前最大利润
for (int i = 0; i < prices.length; i ++) {
if (prices[i] < min) {
min = prices[i];//更新最小值
}
maxProfit = Math.max(maxProfit, prices[i] - min);
}
return maxProfit;
}
}
方法2:动态规划
未优化代码
class Solution {
public int maxProfit(int[] prices) {
int dp[] = new int[prices.length];
dp[0] = 0;
int max = 0;
for (int i = 1; i < prices.length; i++) {
//dp[i]表示在第i天卖出股票能获取到的利润
dp[i] = Math.max(dp[i - 1], 0) + prices[i] - prices[i - 1];
max = Math.max(max, dp[i]);
}
return max;
}
}
优化代码
class Solution {
public int maxProfit(int[] prices) {
int p = 0;
int max = 0;
for (int i = 1; i < prices.length; i++) {
//妈的,写出来这个方程但是不会解释
p = Math.max(p, 0) + prices[i] - prices[i - 1];
max = Math.max(max, p);
}
return max;
}
}