【LeetCode】Best Time to Buy and Sell Stock III

来源:互联网 发布:淘宝上的百乐笔有假吗 编辑:程序博客网 时间:2024/06/07 09:31

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

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).


思路:这个题目只要是从第0个到第n-1个元素进行分割,对前后部分分别求出最大收益,相加然后比较得到最大值。



class Solution {public:int maxProfit(vector<int> &prices) {    int size=prices.size();    if(size<=1)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;}};


0 0
原创粉丝点击