【Leetcode】188. The best time to buy and sell stocks IV (Hard)

1. Title

1. Topic description

You are given an array of integers pricesand an integer k, where prices[i]is the price of a given stock on day iday.

Design an algorithm to calculate the maximum profit you can make. You can complete at most ktransactions. In other words, you can buy up to ktimes and sell up kto times.

NOTE : You cannot participate in multiple trades at the same time (you must sell your previous shares before buying again).

Example 1:

Input: k = 2, prices = [2,4,1]
Output: 2
Explanation: Buy on day 1 (stock price = 2), sell on day 2 (stock price = 4), The profit from this transaction = 4-2 = 2.

Example 2:

Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (stock price = 2), buy on day 3 (stock price = 6 ), the profit from this transaction = 6-2 = 4.
Subsequently, if you buy on the 5th day (stock price = 0) and sell on the 6th day (stock price = 3), the profit from this transaction = 3-0 = 3.

Tips :

おすすめ

転載: blog.csdn.net/u011386173/article/details/132501307