123:best time to Buy and Sell Stock III "Array" "DP"

Source: Internet
Author: User

Title Link: click~

/* Test instructions: An array, the element I represents the price of the stock of day I, allow up to two times to buy and sell, for maximum profit *//** * idea: Record the maximum profit of the day with the Currprofit array, scan the array from start to finish to get the * Currprofit = max (Currpor Fit[i], prices[i]-low) * * Record the maximum profit after the day with a futureprofit array, from the tail to the end of the scan can be * futureprofit = max (Futureprofit[i], high-prices [i]) * * Calculate total Profit: Anx = max (ans, currprofit[i]+futureprofit[i]) */class Solution {Public:int Maxprofit (vector<int        > &prices) {int len = prices.size ();        if (Len <= 1) return 0;        int *currprofit = new Int[len];        int *futureprofit = new Int[len];        Currprofit[0] = futureprofit[len-1] = 0;        Record the maximum profit for the cutoff date int low = Prices[0];            for (int i = 1; i < Len; i + +) {low = min (Low, prices[i]);        Currprofit[i] = max (currprofit[i-1], prices[i]-low);        }//Calculate the maximum profit after the day int high = prices[len-1];            for (int i = len-2; I >= 0; I-) {high = max (high, prices[i]);        Futureprofit[i] = max (futureprofit[i+1], high-prices[i]);    }    Total int ans = 0;        for (int i = 0; i < len; i + +) ans = max (ans, currprofit[i] + futureprofit[i]);    return ans; }};

  

123:best time to Buy and Sell Stock III "Array" "DP"

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.