算法笔记|Day35动态规划VIII
☆☆☆☆☆leetcode 121. 买卖股票的最佳时机
题目分析
1.dp数组含义:dp[i][0]表示第i天不持有股票所得最多现金 ,dp[i][1]表示第i天持有股票所得最多现金;
2.递推公式:dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]+prices[i])(第i天不持有股票所得最多现金要考虑两种情况并取最大值:①第i天卖出,则第i-1天持有为dp[i-1][1],第i天为dp[i-1][1]+prices[i];②第i天未卖出,则第i-1天也没持有,为dp[i-1][0]),dp[i][1]=Math.max(dp[i-1][1],-prices[i])(第i天持有股票所得最多现金要考虑两种情况并取最大值:①第i天购入,则第i-1天前一定没有购入持有为0,第i天为-prices[i];②第i天未购入,则第i-1天也持有,为dp[i-1][1]);
3.初始化:dp[0][0]=0,dp[0][1]=-prices[0];(dp[0][0]表示第0天不持有股票所得现金为0,dp[0][1]表示第0天持有股票所得现金为-prices[0]);
4.遍历顺序:从小到大。
代码
class Solution {
public int maxProfit(int[] prices) {
int dp[][]=new int[prices.length][2];
dp[0][0]=0;
dp[0][1]=-prices[0];
for(int i=1;i<prices.length;i++){
dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]+pri