• leetcode Best Time to Buy and Sell Stock I&&II&&III


    I
    class Solution {
    public:
        int maxProfit(vector<int> &prices) 
        {
            if(prices.size()==0||prices.size()==1)return 0;
            int min=prices[0];
            int max=prices[0];
            int diff=0;
            for(int i=1;i<prices.size();i++)
            {
                if(prices[i]<min)min=prices[i];        
                if(prices[i]-min>diff)diff=prices[i]-min;         
            }
            return diff;
        }
    };
    

    II

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

    III

    class Solution {
    public:
    int maxProfit(vector<int> &prices) {
            int size = prices.size();
            if (size == 0)
                return 0;
            vector<int> f1(size);
            vector<int> f2(size);
            int minV = prices[0];
            for (int i = 1; i < size; i++){
                minV = std::min(minV, prices[i]);
                f1[i] = std::max(f1[i-1], prices[i] - minV);
            }
            int maxV = prices[size-1];
            f2[size-1] = 0;
            for (int i = size-2; i >= 0; i--){
                maxV = std::max(maxV, prices[i]);
                f2[i] = std::max(f2[i+1], maxV - prices[i]);
            }
            int sum = 0;
            for (int i = 0; i < size; i++)
                sum = std::max(sum, f1[i] + f2[i]);
            return sum;
        }
    };

    对于II,即是求所有递增子序列的和,对于III,用两个数组,一个从前往后加,一个从后往前加,求最大值即可。

  • 相关阅读:
    WebView自适应屏幕
    shell脚本:遍历删除
    查看Mysql执行计划
    Spring 源码学习(八) AOP 使用和实现原理
    Java:控制反转(IoC)与依赖注入(DI)
    浏览器-开发者工具
    查看kafka消息消费情况
    shell脚本:遍历删除文本内路径上文件
    聚簇索引与非聚簇索引(也叫二级索引)
    有关MySQL
  • 原文地址:https://www.cnblogs.com/tgkx1054/p/3110347.html
Copyright © 2020-2023  润新知