class Solution {
public int maxProfit(int[] prices) {
int[][] dp = new int[prices.length + 1][2];
dp[0][0] = Integer.MIN_VALUE;
for(int i = 1; i < prices.length + 1;i++){
int price = prices[i - 1];
dp[i][0] = Math.max(dp[i - 1][0],-price);
dp[i][1] = Math.max(dp[i - 1][1],dp[i][0] + price);
}
return dp[prices.length][1];
}
}
dp[i][0]保存当前持有现金,是负值,就是买入的最小值,dp[i][1]储存最大收益
本文介绍了一种通过动态规划解决股票买卖问题的算法,Solution类中的maxProfit方法计算在给定价格数组中获取最大利润的方法。dp[i][0]代表持有现金的最小成本,dp[i][1]储存最大收益。关键在于理解如何利用历史数据来决定何时买入和卖出股票以最大化收益。
402

被折叠的 条评论
为什么被折叠?



