Day42- 动态规划part10 一、买卖股票的最佳时机

一、买卖股票的最佳时机

题目一:121. 买卖股票的最佳时机

121. 买卖股票的最佳时机

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

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

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

维护两个变量

一个是到目前为止所遇到的最低股票价格minPrice

另一个是到目前为止能获得的最大利润maxProfit

遍历价格数组prices,对于每一个价格,首先计算如果在这一天卖出股票能得到的利润(当前价格减去之前的最低价格)

然后更新maxProfit

接着,更新minPrice为当前价格和之前minPrice的较小值

/*
 * @lc app=leetcode.cn id=121 lang=cpp
 *
 * [121] 买卖股票的最佳时机
 */

// @lc code=start
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if (prices.empty()) return 0; 
        int minPrice = prices[0];
        int maxProfit = 0;
        for (int i = 1; i < prices.size(); ++i) {
            if (prices[i] > minPrice) {
                maxProfit = max(maxProfit, prices[i] - minPrice);
            } else {
                minPrice = prices[i];
            }
        }
        return maxProfit;
    }
};
// @lc code=end

题目二:122. 买卖股票的最佳时机  II

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

给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

返回 你能获得的 最大 利润 。

解决方案是遍历价格数组prices,并且只要发现第二天的价格比第一天高,就将这个差值加到总利润中。这样,通过累计所有的正差值(即所有上涨的利润),就能得到可能的最大利润。

/*
 * @lc app=leetcode.cn id=122 lang=cpp
 *
 * [122] 买卖股票的最佳时机 II
 */

// @lc code=start
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int maxProfit = 0;
        for (int i = 1; i < prices.size(); ++i) {
            if (prices[i] > prices[i - 1]) {
                maxProfit += prices[i] - prices[i - 1];
            }
        }
        return maxProfit;
    }
};
// @lc code=end

最近更新

  1. TCP协议是安全的吗?

    2024-02-12 08:54:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-12 08:54:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-12 08:54:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-12 08:54:01       18 阅读

热门阅读

  1. Scrum敏捷培训机构推荐

    2024-02-12 08:54:01       38 阅读
  2. rust入门学习---所有权

    2024-02-12 08:54:01       35 阅读
  3. Rust引用、借用和所有权详解

    2024-02-12 08:54:01       32 阅读
  4. django中如何使用mysql连接池

    2024-02-12 08:54:01       31 阅读
  5. 探索设计模式:原型模式深入解析

    2024-02-12 08:54:01       36 阅读
  6. Web课程学习笔记--jsonp的原理与简单实现

    2024-02-12 08:54:01       41 阅读
  7. Git Push -f 命令详解

    2024-02-12 08:54:01       37 阅读
  8. DataX源码分析 reader

    2024-02-12 08:54:01       34 阅读
  9. 如何让MySQL从部署到稳定运行?

    2024-02-12 08:54:01       35 阅读