【算法|动态规划】Leetcode 121.买卖股票的最佳时机
本文最后更新于 426 天前,其中的信息可能已经有所发展或是发生改变。
32.买卖股票的最佳时机

121.买卖股票的最佳时机


题目描述

  • 给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
  • 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
  • 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0

示例1:

输入: prices = [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。

示例2:

输入: prices = [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

提示:

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

解题思路

第i天有持有和不持有股票两种状态,故采用二维dp数组

  1. 确定dp数组以及下标的含义 dp[i][0] 表示第i持有股票所得的最多现金 dp[i][1] 表示第i不持有股票所得的最多现金
  1. 确定递推公式

    1. i持有股票的情况:dp[i][0],可以由买入不买入两种情况决定

      • 情况1:i买入 股票,那么第 i 天所得现金即第 i 天持有股票所得现金: -price[i]
      • 情况2:i不买入 股票,那么第 i 天所得现金即第 i-1 天持有股票所得现金: dp[i-1][0]
      • 取上述两种情况的最大值,dp[i][0] = max(dp[i-1][0], -price[i])
    2. 第i天不持有股票,dp[i][1],可以由不持有卖出两种情况决定

      • 情况1:i-1不持有股票,那么保持现状,第 i 天所得现金即第 i-1不持有股票所得现金: dp[i-1][1]
      • 情况2:(i-1天持有股票)i卖出股票,第 i 天所得现金即第 i卖出股票所得现金与前一天股票之和:price[i] + dp[i-1][0]
      • 取上述两种情况的最大值,dp[i][1] = max(dp[i-1][1], price[i] + dp[i-1][0]])
  2. dp数组初始化

  3. 根据递推公式:

    • dp[i][0] = max(dp[i-1][0], -price[i])
    • dp[i][1] = max(dp[i-1][1], price[i] + dp[i-1][0]])
    • dp[0][0]:表示第0天持有股票,就是第0天买入,即:dp[0][0] -= price[0]
      dp[0][1]:表示第0天不持有股票,即:dp[0][1] -= 0
  4. 确定遍历顺序

  5. 根据递推公式可以看出,dp[i] 都是由 dp[i-1] 推出来的,那么遍历顺序一定是从前往后遍历。

  6. 打印dp数组

代码实现

  • 核心模式
class Solution{
public:
    int maxProfit(vector<int>& prices){
        int len = prices.size();
        if (len == 0) return 0;
        vector<vector<int>> dp(len, vector<int>(2));

        // initialize the DP array
        dp[0][0] = -prices[0];          // Hold the stock on the first day
        dp[0][1] = 0;                   // No shears held on the first day

        // traversal
        for (int i= 1; i < len; i++){
            dp[i][0] = std::max(dp[i - 1][0], -prices[i]);
            dp[i][1] = std::max(dp[i - 1][1], prices[i] + dp[i - 1][0]);
        }

        return dp[len - 1][1];
    }
};
#include <iostream>
#include "dynamicPro.h"

class Solution{
public:
    int maxProfit(vector<int>& prices){
        int len = prices.size();
        if (len == 0) return 0;
        vector<vector<int>> dp(len, vector<int>(2));

        // initialize the DP array
        dp[0][0] = -prices[0];          // Hold the stock on the first day
        dp[0][1] = 0;                   // No shears held on the first day

        // traversal
        for (int i= 1; i < len; i++){
            dp[i][0] = std::max(dp[i - 1][0], -prices[i]);
            dp[i][1] = std::max(dp[i - 1][1], prices[i] + dp[i - 1][0]);
        }

        print2DVector(dp);              // define in "dynamicPro.h" 

        return dp[len - 1][1];
    }
};

int main(){

    vector<int> case1 = {7, 1, 5, 3, 6, 4};
    vector<int> case2 = {7, 6, 4, 3, 1};

    Solution solution;
    cout << "DP Array = " << solution.maxProfit(case1) << endl;
    cout << "DP Array = " << solution.maxProfit(case2) << endl;

    return 0;
}
  • 输出
DP Array = [[-7, 0], [-1, 0], [-1, 4], [-1, 4], [-1, 5], [-1, 5]]
5
DP Array = [[-7, 0], [-6, 0], [-4, 0], [-3, 0], [-1, 0]]
0

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
下一篇