Leetcode best time to buy and keep stock

Source: Internet
Author: User

Say you have an array for whichITh element is the price of a given stock on dayI.

If you were only permitted to complete at most one transaction (ie, buy one and every one share of the stock), design an algorithm to find the maximum profit.

At the beginning, I thought it was the maximum value minus the minimum value. However, because the purchase occurred before the sale, the minimum value buy and the maximum value sell occurs only when the minimum value is before the maximum value.

The idea of this question is: record the first minimum value of the time, and then max (current element-the first minimum value ).

class Solution {public:    int maxProfit(vector<int> &prices) {        if(prices.size() == 0) return 0;        int res = 0, minv = prices[0];        for(int i = 1; i < prices.size(); ++ i){            res = max(res,prices[i]-minv);            minv = min(prices[i],minv);        }        return res;    }};

You can also consider using dynamic planning for this question.

Set the decision variable to DP [I], which indicates the maximum profit sold by I elements.

The state transition equation is

DP [I + 1] = Prices [I + 1]-Prices [I] + max (0, DP [I])

Since the previous DP [I] is not used after DP [I + 1], you only need a state variable to update it continuously.

class Solution {public:    int maxProfit(vector<int> &prices) {        int dp = 0, res = 0;        for(int i = 1; i < prices.size(); ++ i){            dp = prices[i]-prices[i-1] + max(0,dp);            res = max(res,dp);        }        return res;    }};

 

 

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.