zoukankan      html  css  js  c++  java
  • LeetCode_Best Time to Buy and Sell Stock III

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(prices.size() <2) return 0;
            int *profit = new int[prices.size()];
            memset(profit,0, sizeof(int)*prices.size()) ;
            int i,min,maxProfit = 0,maxValue;
            min = prices[0] ;
            for(i =1; i< prices.size();i++)
            {
                if(prices[i] >= min )
                {
                  maxProfit = max(maxProfit,prices[i]- min ) ;
                  profit[i] = maxProfit ;
                }else
                {
                  profit[i] = maxProfit ;
                  min = prices[i];
                }
            }
            i--;
            maxValue= prices[i] ;
            maxProfit = 0;
            for( i--; i>= 0;i--)
            {
                if(prices[i] < maxValue )
                {
                  maxProfit = max(maxProfit,maxValue - prices[i] );
                  profit[i] += maxProfit ;
                }else
                {
                  profit[i] += maxProfit ;
                  maxValue =  prices[i];
                }
            }
            maxProfit = profit[0];
            for(i=1;i<prices.size();i++)
             if(profit[i] > maxProfit)
                 maxProfit = profit[i] ;
            
            delete []profit ;    
            return maxProfit;
        }
    };

    分析: 这道题主要是求一个分界点,分界点左侧的最大收益和右侧的最大收益之和最大,当然也可能只进行了一次交易。所以上面两边遍历,第一遍遍历求得是分界点左侧的最大收益,第二遍求得是分界点右侧的最大收益。

    --------------------------------------------------------------------天道酬勤!
  • 相关阅读:
    省选后蛤蛤纪事
    About me
    第一篇blog
    震惊!山东一高中生学习锯木板,原因竟是...
    斯特林数相关
    省选后数学学习
    SDOI 2020游记
    奶茶推荐
    Goodbye 2019
    golang 并发锁的陷阱
  • 原文地址:https://www.cnblogs.com/graph/p/3015743.html
Copyright © 2011-2022 走看看