当前位置: 首页 > article >正文

leetcode 123. 买卖股票的最佳时机 III

题目:123. 买卖股票的最佳时机 III - 力扣(LeetCode)

O(N)的算法:

f[i] = max(max(0, prices[i] - min(prices[0], prices[1], ... , prices[i - 1)), f[i - 1]);

g[i] = max(max(0, max(prices[i + 1], prices[i + 2], ... , prices[n - 1])), g[i + 1);

计算最大的 f[i - 1] + g[i] 即可

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = (int) prices.size();
        vector<int> f(n);
        vector<int> g(n);
        
        {
            int min = prices[0];
            f[0] = 0;
            for (int i = 1; i < n; i++) {
                if (prices[i] < min) min = prices[i];
                if (prices[i] - min > 0) {
                    f[i] = prices[i] - min;
                } else {
                    f[i] = 0;
                }
                if (f[i - 1] > f[i]) {
                    f[i] = f[i - 1];
                }
            }
        }
        {
            int max = prices[n - 1];
            g[n - 1] = 0;
            for (int i = n - 2; i >= 0; i--) {
                if (prices[i] > max) max = prices[i];
                if (max - prices[i] > 0) {
                    g[i] = max - prices[i];
                } else {
                    g[i] = 0;
                }
                if (g[i + 1] > g[i]) {
                    g[i] = g[i + 1];
                }
            }
        }
        int t;
        int ret = g[0];
        for (int i = 1; i < n; i++) {
            t = f[i - 1] + g[i];
            if (t > ret) {
                ret = t;
            }
        }
        
        return ret;
    }
};


http://www.kler.cn/a/516900.html

相关文章:

  • Grafana
  • 微信小程序中常见的 跳转方式 及其特点的表格总结(wx.navigateTo 适合需要返回上一页的场景)
  • 入门Stable-Diffusion-WebUI全过程
  • USART_串口通讯轮询案例(HAL库实现)
  • SQL-leetcode—1179. 重新格式化部门表
  • Kingbase数据库体系结构和日常运维监控
  • Windows安装Miniconda和PySide6以及配置PyCharm
  • 0基础跟德姆(dom)一起学AI 自然语言处理21-fasttext模型架构
  • OpenVela 架构剖析:从内核到应用
  • 阿里云-银行核心系统转型之业务建模与技术建模
  • 大数据学习(38)- Flink运行时架构
  • ChatGPT大模型极简应用开发-CH4-GPT-4 和 ChatGPT 的高级技巧
  • SQL记录学习日志
  • 我谈《概率论与数理统计》的知识体系
  • python flask中使用or查询和and查询,还有同时使用or、and的情况
  • Vue实现div滚动,并且支持top动态滚动
  • windows修改host上github
  • 考研408笔记之数据结构(五)——图
  • 第04章 02 VTK管道的执行过程与类型
  • 2.7 createCmd中的visitor访问者设计模式