zoukankan      html  css  js  c++  java
  • LeetCode-Best Time to Buy and Sell Stock III

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete at most two transactions.

    Note:
    You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    总共可以买卖两次,手中同时最多持有一股

    先找出只买卖一次的解,将区间分为三段,第二次买卖发生在前一段或者后一段,或者第一次与第二次都在当前第一次之中

    class Solution {
    public:
        int sub(vector<int>& prices,int s,int e,int& is,int& ie){
            if(e<=s){
                return 0;
            }
            //find max
            int max1=0,min1=prices[s];
            int tmps=s;
            is=-1,ie=-1;
            for(int i=s+1;i<=e;i++){
                if(prices[i]>=min1){
                    if(max1<prices[i]-min1){
                        max1=prices[i]-min1;
                        is=tmps;
                        ie=i;
                    }
                }
                else{
                    min1=prices[i];
                    tmps=i;
                }
            }
            if(ie==-1)return 0;
            return max1;
        }
        int sub2(vector<int>& prices,int s,int e,int& is,int& ie){
            if(e<=s){
                return 0;
            }
            //find max
            int max1=0,min1=prices[e];
            int tmpe=e;
            is=-1,ie=-1;
            for(int i=e-1;i>=s;i--){
                if(prices[i]>=min1){
                    if(max1<prices[i]-min1){
                        max1=prices[i]-min1;
                        is=i;
                        ie=tmpe;
                    }
                }
                else{
                    min1=prices[i];
                    tmpe=i;
                }
            }
            if(is==-1)return 0;
            return max1;
        }
        int maxProfit(vector<int> &prices) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            if(prices.size()==0){
                return 0;
            }
            //find max
            int start,end;
            int m1=sub(prices,0,prices.size()-1,start,end);
            if(m1==0)return 0;
            int m2,m3,m4;
            int tmp1,tmp2;
            m2=sub(prices,0,start-1,tmp1,tmp2);
            m3=sub(prices,end+1,prices.size()-1,tmp1,tmp2);
            m4=sub2(prices,start,end,tmp1,tmp2);
            int ret=m1+m2;
            if(m1+m3>ret)ret=m1+m3;
            if(m1+m4>ret)ret=m1+m4;
            return ret;
        }
    };
    View Code
  • 相关阅读:
    Android strings.xml中定义字符串显示空格
    Android各国语言对照表(values-xxx)
    SimInfo获取(MCC, MNC, PLMN)
    Android APN
    Android studio 运行java程序
    [MyBatis]DAO层只写接口,不用写实现类
    idea代码调试debug篇
    比较分析 Spring AOP 和 AspectJ 之间的差别
    maven进阶:一个多模块项目
    Maven最佳实践:划分模块
  • 原文地址:https://www.cnblogs.com/superzrx/p/3355505.html
Copyright © 2011-2022 走看看