27. Best time to buy and stock Stock & best time to buy and stock Stock II & best time to buy and stock Stock III

Source: Internet
Author: User
Best time to buy and buy stock

(Onlinejudge: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock)

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.

Note: Restrictions: buy first and then sell (different days ).

Thought: After buying, 1. If the price remains the same in the future, do not buy or not sell. 1. If the price is lower, buy again. 2. When the price increases, let's assume that the selling is done and update the profit value.

class Solution {public:    int maxProfit(vector<int> &prices) {        int buy = 0x7fffffff, maxProfile = 0;        for(int i = 0; i < prices.size(); ++i) {            if(prices[i] == buy) continue;            if(prices[i] < buy) { buy = prices[i]; continue; }            else maxProfile = max(maxProfile, prices[i]-buy);        }        return maxProfile;    }};

 

Best time to buy and stock Stock II

(Onlinejudge: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii)

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

Design an algorithm to find the maximum profit. you may complete as your transactions as you like (ie, buy one and every one share of the stock multiple times ). however, you may not engage in multiple transactions at the same time (ie, you must wait the stock before you buy again ).

Thought: Calculate the sum of the absolute values of all non-decreasing sequences. The code and proof I posted on leedcode:

class Solution {public:    int maxProfit(vector<int> &prices) {        int n = prices.size();        if(n == 0) return 0;        int start = 0, profile = 0;        for(int i = 1; i < n; ++i) {            if(prices[i] < prices[i-1]) {                profile += prices[i-1] - prices[start];                start = i;            }        }        profile += prices[n-1] - prices[start];        return profile;    }};/*********************** *provement ***************//*Explain the code I pasted above: From left to right I find out every subsequence that not exist decrease. such as: l ... k1 ...k2 ... h (l <=...<= k1 <= ... k2 <= ... <= h)In this sequence: ( k1-l ) + ( h-k2 ) = ( h-l ) - ( k2-k1 ) <= ( h-l ); So (h - l) will be the maximum profit in this days.Another case:L1 ...d1... H1 K2 ...k... K3 L2 ...d2... H2 (L1 <=... H1 > K2 >=...k >=... K3 > L2 <=... H2 )K2 ... K3 is not exist increase sequence.then for any k in that position,( k-d1 ) + ( d2-k ) <= ( K2-L1 ) + ( H2-K3 ) < ( H1-L1 ) + ( H2-L2 ) In my code, variant "start" is the start of every no decrease sequence.*/

A little adjustment.

class Solution {public:    int maxProfit(vector<int> &prices) {        int start = 0, profile = 0;        for(size_t i = start+1; i < prices.size(); ++i) {            if(prices[i] < prices[i-1]) {                profile += prices[i-1] - prices[start];                start = i;            }            else if(i+1 == prices.size())                 profile += prices[i] - prices[start];        }        return profile;    }};

 

Best time to buy and buy stock III

(Onlinejudge: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii)

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

Design an algorithm to find the maximum profit. You may complete at mostTwoTransactions.

Note:You may not engage in multiple transactions at the same time (ie, you must encrypt the stock before you buy again ).

Idea: dynamic planning. Record the maximum profit before the start of each position (inclusive) and the maximum profit from the beginning to the end.

class Solution {public:    int maxProfit(vector<int> &prices) {        vector<int> preProfile(prices.size()+2, 0), postProfile(prices.size()+2, 0);                int minPrice = 0x7fffffff;        for(size_t i = 1; i <= prices.size(); ++i) {            minPrice = min(minPrice, prices[i-1]);            preProfile[i] = max(prices[i-1] - minPrice, preProfile[i-1]);        }                int maxPrice = 0;        for(int i = prices.size(); i >= 1; --i) {            maxPrice = max(maxPrice, prices[i-1]);            postProfile[i] = max(maxPrice - prices[i-1], postProfile[i+1]);        }                int maxProfile = 0;        for(size_t i = 1; i <= prices.size(); ++i)             maxProfile = max(maxProfile, preProfile[i] + postProfile[i]);        return maxProfile;    }};

 

27. Best time to buy and stock Stock & best time to buy and stock Stock II & best time to buy and stock Stock III

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.