best time to buy and sell stock 3---leetcode

Source: Internet
Author: User

Topic:

Say you has an array for which the i-th element is the price of a given-stock on day I.

design an algorithm to find the maximum profit. Most two  transactions.

Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).

Train of thought: This time limit the number of times that can be a day for the demarcation point before this day the biggest profit and the biggest profit after this day of the two profit and become the largest profit of two trades

#include <iostream> #include <vector>using namespace std;/* ideas: You can divide two times into history and the future from one day to the beginning of the best profit and the future of the best profit of the two and The best profit */int Sellstockthird (vector<int>& vec) {vector<int> Share (vec.size (), 0) for trading two times; vector<int > His (vec.size (), 0); Vector<int>fur (Vec.size (), 0); int i,j=0;for (I=1;i<vec.size (); i++) Share[i] = vec[i]- Vec[i-1];int Cur=share[0];int sum = share[0];for (I=1;i<vec.size (); i++) {if (cur < 0) cur = share[i];else{cur+=share [I];his[i] = cur;} if (sum < cur) {sum = cur; his[i] = sum;} else his[i] = his[i-1];} cur = share[share.size () -1];sum = Cur;for (I=vec.size () -2;i>=0;i--) {if (cur < 0) cur = share[i];else{cur+=share[i]; Fur[i] = cur;} if (sum < cur) {sum = cur; fur[i] = sum;} else fur[i] = fur[i+1];} Sum =0;for (i=0;i
now we can trade up to two times. We still use dynamic programming to do this, and in fact we can solve the very general situation, that is, the maximum number of K transactions.
Here we first explain the maximum number of possible K-trading algorithms, and then up to two times we just need to take K to 2. We still use "local optimal and global optimal solution". We maintain two kinds of quantities, one is the current arrival on the first day can be a maximum of J transactions, the best profit is how much (Global[i][j]), the other is the current arrival of the first day, up to J-trade, and the last trade on the day to sell the best profit is how much (Local[i][j]). Let's look at the recursive, the global is relatively simple,

Global[i][j]=max (Local[i][j],global[i-1][j]),that is to go to the current part of the best, and the best in the past the largest of the big one (because the last deal if the current day must be in the local best inside, otherwise must be in the past global optimal inside). For the maintenance of local variables, the recursive type is
Local[i][j]=max (Global[i-1][j-1]+max (diff,0), Local[i-1][j]+diff),That is , look at two, the first is the global to I-1 day j-1 transactions, and then add today's deal, if today is to make money (that is, as long as the j-1 transaction, the last time to take the current day), the second is to take the local i-1 days J transactions, Then add today's difference (here because local[i-1][j], for example, contains the sale of I-1 day, so now becomes the day I sell, does not increase the number of trades, and here whether the diff is greater than 0 must be added, because otherwise will not meet LOCAL[I][J] Conditions that must be sold on the last day).
The above algorithm for the number of days need a scan, and each time to the number of transactions to be recursive solution, so the time complexity is O (n*k), if the maximum of two transactions, then the complexity of O (n). Space only need to maintain the day data can be, so is O (k), when k=2, then is O (1). The code is as follows:
    public int Maxprofit (int[] prices) {          if (Prices==null | | prices.length==0)              return 0;          int[] Local = new INT[3];          int[] Global = new int[3];          for (int i=0;i<prices.length-1;i++)          {              int diff = prices[i+1]-prices[i];              for (int j=2;j>=1;j--)              {                  Local[j] = Math.max (global[j-1]+ (diff>0?diff:0), Local[j]+diff);                  GLOBAL[J] = Math.max (Local[j],global[j]);              }          }          return global[2];      }  


Best time to buy and sell stock 3---leetcode

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.