Leetcode of dynamic programming (DP) -121 topic. The best time to buy and sell stocks (Best Time to Buy and Sell Stock)

Leetcode of dynamic programming (DP) -121 topic. The best time to buy and sell stocks (Best Time to Buy and Sell Stock)

Stock issues:

121. The best time to stock trading

122. The best time to trade stocks II

III 123. the best time to buy and sell stocks

188. The best time to buy and sell stocks IV

309. The best time to buy and sell shares with the freezing of

714. The best time to buy and sell stocks with fee


 

Given an array, its first  i  -th element is given a share of the  i  -day price.

If you are only allowed up to complete a transaction (ie buying and selling a stock), to design an algorithm to compute the maximum profit you can get.

Note that you can not sell the stock before buying stocks.

Example 1:

Input: [7,1,5,3,6,4] 
Output: 5 
Explanation: Day 2 (= 1 stock price), when buying, on day 5 (stock price = 6), when sold, The maximum profit = 6-1 = 5. 
     Note that profits can not be 7-1 = 6, because the selling price must be greater than the purchase price.

Example 2:

Enter: [7,6,4,3,1] 
Output: 0 
to explain: In this case, no transaction is completed, the maximum profit is zero.

This question requires only two for loops, to find two numbers, the difference between the maximum and the difference> 0 then ok. 

By dp do:
dp [i] [j] [k] represents the i-th day, I have j stocks, the maximum limit trading k times
this question in k = 1 j = 0 or 1

Detailed Look Transaction Costs stock issue .

class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null || prices.length == 0) return 0;
        int k = 1;
        int[][][] dp = new int[prices.length][2][k+1];
        dp[0][0][0] = 0;
        dp[0][1][1] = -prices[0];

        for (int i = 1; i < prices.length; i++) {
            dp[i][0][k] = Math.max(dp[i-1][1][k]+prices[i],dp[i-1][0][k]);
            dp[i][1][k] = Math.max(dp[i-1][0][k-1]-prices[i],dp[i-1][1][k]);
        }
        return dp[prices.length-1][0][k];
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11487741.html