LeetCode 188. Best Time to Buy and Sell Stock IV

Post by ailswan Oct.25, 2023

188. Best Time to Buy and Sell Stock IV*

Problem Statement

link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ https://leetcode.cn/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, and an integer k.

Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times.

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

Example:

Input: k = 2, prices = [2,4,1] Output: 2

Input: k = 2, prices = [3,2,6,5,0,3] Output: 7

Solution Approach

Algorithm

Implement

    class Solution: