【LeetCode】188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时机 IV(Hard)(JAVA)

【LeetCode】188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时机 IV(Hard)(JAVA)

题目地址: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/

题目描述:

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Notice that you may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:

Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.

Constraints:

  • 0 <= k <= 109
  • 0 <= prices.length <= 1000
  • 0 <= prices[i] <= 1000

题目大意

给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

解题方法

  1. 采用动态规划,找出动态规划函数
  2. 一个三维数组表示交易的情况 dp[i][j]: 表示前面 i 个股票,做多交易 j 次;dp[i][j][0]: 表示当前持有股票; dp[i][j][1]: 表示当前不持有股票
  3. 加入 dp[i][j] 之前的状态都已经计算出来了。 dp[i][j][0] , 要么这一次不交易:dp[i - 1][j][0]; 要么这一次交易:dp[i][j - 1][1] + prices[i],求出最大值即可。同理也可以求出 dp[i][j][1]
class Solution {
    public int maxProfit(int k, int[] prices) {
        if (prices.length <= 1) return 0;
        // dp[i][j][0]: no stock; dp[i][j][1]: has stock;
        int[][][] dp = new int[prices.length][k + 1][2];
        for (int i = 0; i < prices.length; i++) {
            for (int j = 0; j <= k; j++) {
                if (i == 0) {
                    dp[i][j][0] = 0;
                    dp[i][j][1] = -prices[i];
                } else if (j == 0) {
                    dp[i][j][0] = 0;
                    dp[i][j][1] = Math.max(-prices[i], dp[i - 1][j][1]);
                } else {
                    dp[i][j][0] = Math.max(dp[i - 1][j][0], dp[i][j - 1][1] + prices[i]);
                    dp[i][j][1] = Math.max(dp[i - 1][j][0] - prices[i], dp[i - 1][j][1]);
                }
            }
        }
        return dp[prices.length - 1][k][0];
    }
}

执行耗时:9 ms,击败了54.92% 的Java用户
内存消耗:41.1 MB,击败了16.91% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
【LeetCode】188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时机 IV(Hard)(JAVA)
上一篇:组合总和 IV


下一篇:记登录注册时候 前端js明文密码 加密传输 php解密