zoukankan      html  css  js  c++  java
  • [leetcode]Best Time to Buy and Sell Stock III

    本来想枚举断开点,然后像I那样算,然后加起来求最大就好了。。。

    但是TLE。。。

    想了下,其实枚举断开点,重复计算了好多。。。

    那就先记录下来就好了。。。

    f,g两个数组,分别记录左右两边的最大值。。。

    然后再枚举。。。

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int size = prices.size();
            if(size < 2) return 0;
            vector<int> f(size , 0); //left
            vector<int> g(size , 0); // right;
            
            //init f
            int profit = 0;
            int currmin = prices[0];
            for(int i = 1 ; i < size ; i++){
                profit = max(profit , prices[i] - currmin);
                currmin = min(currmin , prices[i]);
                f[i] = profit;
            }
            //init g
            int currmax = prices[size-1];
            profit = 0;
            for(int i = size - 1 ; i >= 0 ; i --){
                profit = max(profit , currmax - prices[i]);
                currmax = max(currmax , prices[i]);
                g[i] = profit;
            }
            profit = 0;
            for(int i = 0 ; i < size ; i ++){
                profit = max(profit , f[i] + g[i]);
            }
            return profit;
        }
    };
  • 相关阅读:
    python基础学习1-函数相关
    python基础学习1-SET 集合
    Linux命令学习笔记1
    python基础学习1-字典的使用
    python基础学习1-列表使用
    Jzoj4743 积木
    Jzoj4786 小a的强迫症
    Jzoj4746 树塔狂想曲
    Jzoj5246 Trip
    Jzoj5245 Competing Souls
  • 原文地址:https://www.cnblogs.com/x1957/p/3507931.html
Copyright © 2011-2022 走看看