[Leetcode] [Java] best time to Buy and Sell Stock IV

Source: Internet
Author: User

Title:

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

Test Instructions:

Given an array of element I elements in an array, represents the price of a given stock at the first day.

Design an algorithm to find the maximum benefit. You are allowed to trade up to K Times.

Attention:

You cannot make multiple trades at the same time. (That is, you must sell the stock before you can buy it again.)


Algorithm Analysis:

Using dynamic programming to solve, use local optimal and global optimal solution

Because of the number of transactions to consider, the maintenance amount should be a two-dimensional array.

Define Maintenance Amount:

GLOBAL[I][J]: maximum profit for J-trades at the time of arrival, this is the global optimal

LOCAL[I][J]: The maximum profit for a maximum of J transactions and the last sale on the last day at the time of arrival is the local optimal

To define a recursive type:

Global[i][j]=max (Global[i-1][j],local[i][j]), that is, the day I have no transaction, and the first day of trading

local[i][ J]=max (Global[i-1][j-1]+max (diff,0), Local[i-1][j]+diff) diff=price[i]-price[i-1];

Two is taken from the local i-1 day J Trade, and then add today's difference (here because local[i-1][j], for example, contains the sale of the i-1 day, so now becomes the day I sell, does not increase the number of transactions,

And here whether the diff is greater than 0 must be added, because otherwise will not meet LOCAL[I][J] must be sold on the last day of the condition)

This problem also has a pit, is if the value of K is much larger than prices days, such as K is good millions of, and prices days for a few days, the above DP solution is very inefficient, should be directly used

"Best time to Buy and Sell Stock II" method to solve, so the problem is actually the previous two and three complexes.


AC Code:

<span style= "Font-family:microsoft yahei;font-size:12px;"            >public class Solution {public int maxprofit (int k, int[] prices) {if (Prices==null | | prices.length==0)        return 0;                 if (K>prices.length)//k Times is greater than the number of days, the conversion to the question "best time to Buy and Sell Stock II"--infinite trading Scenario {if (prices==null)            return 0;            int res=0;                for (int i=0;i<prices.length-1;i++) {int degit=prices[i+1]-prices[i];            if (degit>0) res+=degit;        } return res; }/* Definition of maintenance: GLOBAL[I][J]: Maximum profit for J-transactions can be made on the arrival of day I, this is the global best local[i][j]: The maximum number of J transactions to be made on the first day of arrival and the last sale Profit, this is the local optimal definition of recursion: Global[i][j]=max (Global[i-1][j],local[i][j]), that is, the first day no transaction, and the day I have a transaction Local[i][j]=max (global[i-1][       J-1]+max (diff,0), Local[i-1][j]+diff) diff=price[i]-price[i-1];        */int[][] global=new int[prices.length][k+1]; Int[][] Local=new Int[prices.leNGTH][K+1];            for (int i=0;i<prices.length-1;i++) {int diff=prices[i+1]-prices[i]; for (int j=0;j<=k-1;j++) {Local[i+1][j+1]=math.max (Global[i][j]+math.max (diff,0), local[i][j+1                ]+diff);            Global[i+1][j+1]=math.max (global[i][j+1],local[i+1][j+1]);    }} return global[prices.length-1][k]; }}</span>


Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode] [Java] 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.