121. 买卖股票的最佳时机

121. 买卖股票的最佳时机

题目链接:121. 买卖股票的最佳时机(简单)

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0

示例 1:

输入:[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 <= 105

  • 0 <= prices[i] <= 104

解题思路

贪心

因为股票就买卖一次,那么贪心的想法很自然就是取最左最小值,取最右最大值,那么得到的差值就是最大利润。

C++

// 贪心算法
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int low = INT_MAX;
        int result = INT_MIN;
        for (int i = 0; i < prices.size(); i++) {
            low = min(low, prices[i]);
            result = max(result, prices[i] - low);
        }
        return result;
    }
};

JavaScript

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let result = Number.MIN_VALUE;
    let low = Number.MAX_VALUE;
    for (let i of prices) {
        low = Math.min(low, i);
        result = Math.max(result, i - low);
    }
    return result;
};
  • 时间复杂度:O(n)

  • 空间复杂度:O(1)

动态规划

动态规划五部曲,详细在代码注释中。

C++

// 动态规划
class Solution1 {
public:
    int maxProfit(vector<int>& prices) {
        // 1. dp[i][0]表示第i天持有(持有并不代表在当天买入,也可能是之前买入的)股票的最大金额
        //    dp[i][1]表示第i天不持有(不持有表示在第i天之前(包括第i天)已经卖出,或者从未买入)股票的最大金额
        vector<vector<int>> dp(prices.size(), vector<int>(2));
        // 3. dp数组的初始化:对于第一天的股票,要么买,要不买,不存在卖。
        //    所以dp[0][0] = -prices[0](持有),dp[0][1] = 0(不持有)
        dp[0][0] = -prices[0];
        dp[0][1] = 0;
        // 4. 遍历顺序:从前向后
        for (int i = 1; i < prices.size(); i++) {
            // 2. 递推公式:
            // dp[i][0]表示第i天持有股票的最大金额。第i天能够持有股票的情况有2种:第i-1天就持有股票(保持现状),或者第i天买入股票。
            // 即在这两种情况中取最大值。(说明:买入股票得花钱,所以金额为负)
            dp[i][0] = max(dp[i - 1][0], -prices[i]);
            // dp[i][1]表示第i天不持有股票的最大金额。第i天不持有股票的情况有2种:第i-1天就不持有股票(保持现状),或者第i天卖出股票。
            // 第i天卖出股票,所得到的金额就是以第i天股票价格卖出后得到的现金。
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
        }
        return dp[prices.size() - 1][1];
    }
};

JavaScript

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    const dp = Array(prices.length).fill().map(item => Array(2).fill());
    dp[0][0] = -prices[0];
    dp[0][1] = 0;
    for (let i = 1; i < prices.length; i++) {
        dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
        dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
    }
    return dp[prices.length - 1][1];
};
  • 时间复杂度:O(n)

  • 空间复杂度:O(n)

posted @ 2022-03-11 11:06  wltree  阅读(84)  评论(0编辑  收藏  举报