best time to Buy and Sell Stock iv****

Source: Internet
Author: User

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. Transactions at the most K.

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

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Analyse:assume Global[i][j] represents the maximum profit at day I with J transactions, Local [I][j] is the maximum ProFi T at day I with J transactions at the last transaction occurred in Day I. Then we had: global[i][j] = max (Local[i][j], global[i-1][j]) (the left one was doing the transaction at day I W Hile the right one isn't doing the transaction at day i), local[i][j] = max (local[i-1][j] + diff, Global[i-1][j- 1] + max (0, diff)). (We have to does the j-th transaction on day I, so if we already did J transactions at day I-1 and does the last Transactio N on the (i-1) th day, or we do j-1 transactions by the (i-1) th day, then we choose the larger one.

Runtime:8ms.

1 classSolution {2  Public:3     intMaxprofit (intK, vector<int>&prices) {4         if(Prices.size () <=1|| K = =0)return 0;5                 6         intresult =0;7         if(k >= prices.size ()) {//cannot do k transactions, then does all operations which can earn money8              for(inti =1; I < prices.size (); i++){9                 if(Prices[i] > Prices[i-1])TenResult + = Prices[i]-prices[i-1]; One             } A             returnresult; -         } -         the         Const intn = k +1; -         intL[n] = {0}, G[n] = {0}; -          -          for(inti =0; I < prices.size ()-1; i++){ +             intdiff = prices[i +1] -Prices[i]; -              for(intj = k; J >=1; j--){ +L[J] = max (G[j-1] + MAX (0, diff), L[j] +diff); AG[J] =Max (L[j], g[j]); at             } -         } -         returnG[k]; -     } -};

best time to Buy and Sell Stock iv****

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.