Leetcode -- best time to buy and buy stock III maximum share profit (AC)

Source: Internet
Author: User

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 encrypt the stock before you buy again ).

It should be noted that you can operate twice, but the second purchase can only be performed after the first sale. Therefore, the idea is to use the greedy algorithm to calculate the maximum possible benefits of buying and selling each day, and record the results in an array. Calculate the maximum possible benefits of buying and selling each day in reverse order, and record the results in an array. Then, the sum of the benefits that can be achieved in the two situations corresponding to each day in the two arrays is obtained, and the maximum value is the maximum benefit that can be achieved. The Code is as follows:

class Solution {public:    int maxProfit(vector<int> &prices) {        if(prices.empty())            return 0;        int n = prices.size();        vector<int> pre(n,0);        vector<int> post(n,0);        int curMin = prices[0];        int curMax = prices[n-1];        int result=0;        for(int i=1; i<n; i++)        {            curMin = curMin<prices[i] ? curMin : prices[i];            int diff = prices[i]-curMin;            pre[i] = pre[i-1]>diff ? pre[i-1] : diff;        }        for(int i=n-2; i>=0; i--)        {            curMax = curMax>prices[i] ? curMax : prices[i];            int diff = curMax-prices[i];            post[i] = post[i+1]>diff ? post[i+1] : diff;        }        for(int i=1; i<n; i++)        {            result = result>(pre[i]+post[i]) ? result : (pre[i]+post[i]);        }        return result;    }};


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.