leetcode No123. Best Time to Buy and Sell Stock III

来源:互联网 发布:ios降级会丢失数据吗 编辑:程序博客网 时间:2024/05/18 02:46

Question:

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

数组中的元素表示当天股票价格,只允许两次交易(买入卖出),且不能在同一时间交易两次,求最大利润。

Algorithm:

prices[i]的最大利润res是,数组i之前的最大利润和i之后的最大利润之和。从前往后遍历一次,记录i之前的最大利润。从后往前遍历一次,记录i之后的最大利润。并更新两次最大利润之和的最大值。

Accepted Code:

class Solution {  //只允许两次交易,从前遍历一次,从后遍历一次,刚好是i位置前后的maxpricepublic:    int maxProfit(vector<int>& prices) {        if(prices.size()<2)return 0;        int N=prices.size();        int min=prices[0];        int max1=0;        vector<int> res(N,0);        for(int i=1;i<N-1;i++)        //从前往后遍历        {            if((prices[i]-min)>max1)                max1=prices[i]-min;            if(prices[i]<min)                min=prices[i];            res[i]=max1;        }        int max2=0;        int temp=prices[N-1];   //最大值        int finalmax=0;        for(int j=N-2;j>=0;j--)      //从后往前遍历        {            if((temp-prices[j])>max2)                max2=temp-prices[j];            if(prices[j]>temp)                temp=prices[j];            if((res[j]+max2)>finalmax)                finalmax=res[j]+max2;        }        return finalmax;    }};



0 0