力扣:122. 买卖股票的最佳时机 II

动态规划思路: 

1.先声明一个dp数组来表示在下标为i时手中有无股票的最大利润,dp【i】【0】表示为在下标为i时,手中没有股票。dp【i】【1】表示为在下标为i时,手中有股票。

2.在这题中我们要判断两种情况分别是在下标i时手中有股票的最大利润,递推公式:dp[i][1]=Math.max(dp[i-1][0]-prices[i],dp[i-1][1]); 。另一个为下标i时手中没有股票的最大利润,递推公式:dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]+prices[i])。最后返回dp【length-1】【0】的值,不能返回dp【length-1】【1】的值,因为手中还有股票没有卖,利润没有到最大

​
class Solution {
    public int maxProfit(int[] prices) {
        //定义一个dp数组来表示在下标为i时手中有无股票的最大利润
        int[][] dp=new int[prices.length][2];
        //初始化下标为0时的手中有无股票的状态
        //在下标为0时手中没有股票
        dp[0][0]=0;
        //在下标为0时手中有股票
        dp[0][1]=-prices[0];
        //for循环来遍历dp数组
        for(int i=1;i<prices.length;i++){
            //递推公式,来计算每一个下标下的dp数组值。
            //dp[i][0]表示在下标为i时手中没有股票
             dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
             //dp[i][1]表示在下标为i时手中有股票
            dp[i][1]=Math.max(dp[i-1][0]-prices[i],dp[i-1][1]);
        }
     return dp[prices.length-1][0];
    }
}

​

相关推荐

  1. 122. 买卖股票最佳时机 II

    2024-02-17 06:14:02       58 阅读
  2. 122. 买卖股票最佳时机 II

    2024-02-17 06:14:02       51 阅读
  3. [题解]122. 买卖股票最佳时机 II

    2024-02-17 06:14:02       37 阅读
  4. 123. 买卖股票最佳时机 III

    2024-02-17 06:14:02       57 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-17 06:14:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-17 06:14:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-17 06:14:02       82 阅读
  4. Python语言-面向对象

    2024-02-17 06:14:02       91 阅读

热门阅读

  1. 【前端工程化面试题】说一下 webpack 的构建流程

    2024-02-17 06:14:02       65 阅读
  2. 使用 C++23 从零实现 RISC-V 模拟器(6):权限支持

    2024-02-17 06:14:02       44 阅读
  3. python自动定时任务schedule库的使用方法

    2024-02-17 06:14:02       53 阅读
  4. 搜索引擎枚举

    2024-02-17 06:14:02       57 阅读
  5. ACP科普:敏捷开发之kanban

    2024-02-17 06:14:02       44 阅读
  6. OpenAI 生成视频模型 Sora 论文翻译

    2024-02-17 06:14:02       46 阅读
  7. uniapp如何给视频组件设置图片

    2024-02-17 06:14:02       48 阅读
  8. ubantu 新建.sh 文件

    2024-02-17 06:14:02       48 阅读