LeetCode121/122/123 Best Time to Buy and Stock (Stock) I/II/III----DP + Greedy **

Source: Internet
Author: User

LeetCode121/122/123 Best Time to Buy and Stock (Stock) I/II/III----DP + Greedy **

I. LeetCode 121 Best Time to Buy and Stock

Question:

Say you have an array for which the ith element is the price of a given stock on day I.

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.

Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

Analysis: This question is to select the maximum benefit for buying and selling stocks. The maximum benefit for selling stocks on the I day is the stock price on the I day minus [0, i-1] The minimum stock price within the day, when the stock price on day I is lower than the lowest price in the paint, the lowest stock price is updated. Then the biggest stock market benefit is the DP problem. If profit [I] is used to represent the benefits of day I, minBuyPrice = min (minBuyPrice, prices [I]) and profit [I] = prices [I]-minBuyPrice. then, the maximum value in profit is obtained.

 

Class Solution {public: int maxProfit (vector
 
  
& Prices) {int n = prices. size (); if (n = 0) return 0; int maxPro = 0; int minBuyPrice = prices [0]; for (int I = 1; I <n; I ++) {minBuyPrice = min (minBuyPrice, prices [I]); // used to record the minimum value bought in the current day minBuyPrice [I + 1] = min (minBuyPrice [I], nums [I]) if (maxPro <(prices [I]-minBuyPrice) {// is the global maximum benefit less than the current day's benefit maxPro = prices [I]-minBuyPrice ;}} return maxPro ;}};
 

II. LeetCode 122 Best Time to Buy and Stock II

 

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

Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

Analysis: This question is the deformation of the above question. There is no limit on the number of purchases and sales, but the second purchase must be after the time node of the first sale, there is a local optimum, that is, 2 4 5 3 6 8. At this time, 8-2 must be smaller than 5-2 + 8-3. Therefore, the incremental benefit of the array is the local optimum, then, the sum of all local optimizations is global optimization.

 

Class Solution {public: int maxProfit (vector
 
  
& Prices) {int n = prices. size (); if (n = 0) return 0; int minBuyPrice = prices [0]; int sumResult = 0;/* for (int I = 0; I <n; I ++) {if (I + 1 <n & prices [I]> = prices [I + 1]) {// when prices [I]> = prices [I + 1] sumResult + = prices [I]-minBuyPrice; // both prices [I]-minBuyPrices can be used to find the local optimum. -- all of them add up to the global optimal solution. minBuyPrice = prices [I + 1];} else {if (I + 1 = n) sumResult + = prices [I]-minBuyPrice;} */for (int I = 1; I <n; I ++) {if (prices [I] <prices [I-1]) {// There is a local optimum at I, all local optimum sum is global optimum sumResult + = prices [I-1]-minBuyPrice; minBuyPrice = prices [I];} sumResult + = prices [n-1]-minBuyPrice; return sumResult ;}};
 
Later I saw a piece of awesome code in discuss: 10 lines:

 

 

class Solution {public:    int maxProfit(vector
 
   &a) {        int profit = 0;        for (int i = 1; i < a.size(); ++i) {            if (a[i] > a[i-1]) {                profit += a[i]-a[i-1];            }        }        return profit;    }};
 
III. LeetCode 123 Best Time to Buy and Stock III

 

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

Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

Analysis: this is the question of deformation, that is, the maximum number of transactions is two. Of course, there are two methods. The first method is brute force. For each I, we seek two benefits for [0, I] and [I, n-1], then sum and traverse I, it can take the maximum value, which requires O (N ^ 2) time. The second method is dynamic planning. Two arrays are used. The first array f1 [I] is used to indicate the maximum benefit of buying and selling in [0, I, f2 [I] indicates the maximum benefit of buying and selling in [I, n-1. Then the maximum benefit is max (f1 [I] + f2 [I]). The method for finding f1 [I] and f2 [I] has been given.

 

Class Solution {public: int maxProfit (vector
 
  
& Prices) {int n = prices. size (); if (n <= 1) return 0; vector
  
   
F1 (n); // indicates the maximum profit vector that can be obtained by buying and selling data in [0, I ].
   
    
F2 (n); // indicates that the maximum profit result obtained by buying and selling in [I, n-1] Is max (f1 [I] + f2 [I]). int minPrice = prices [0]; for (int I = 1; I <n; I ++) {minPrice = min (minPrice, prices [I]); f1 [I] = max (f1 [I-1], prices [I]-minPrice);} int maxPrice = prices [n-1]; for (int I = n-2; i> = 0; I --) {// traverse maxPrice = max (maxPrice, prices [I]) from the back. f2 [I] = max (f2 [I + 1], maxPrice-prices [I]);} int maxResult = 0; for (int I = 0; I <n; I ++) maxResult = max (maxResult, f1 [I] + f2 [I]); return maxResult ;}};
   
  
 


 

 

 

 

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.