LeetCode in Kotlin

3573. Best Time to Buy and Sell Stock V

Medium

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

You are allowed to make at most k transactions, where each transaction can be either of the following:

Note that you must complete each transaction before starting another. Additionally, you can’t buy or sell on the same day you are selling or buying back as part of a previous transaction.

Return the maximum total profit you can earn by making at most k transactions.

Example 1:

Input: prices = [1,7,9,8,2], k = 2

Output: 14

Explanation:

We can make $14 of profit through 2 transactions:

Example 2:

Input: prices = [12,16,19,19,8,1,19,13,9], k = 3

Output: 36

Explanation:

We can make $36 of profit through 3 transactions:

Constraints:

Solution

import kotlin.math.max

class Solution {
    fun maximumProfit(prices: IntArray, k: Int): Long {
        val n = prices.size
        var prev = LongArray(n)
        var curr = LongArray(n)
        for (t in 1..k) {
            var bestLong = -prices[0].toLong()
            var bestShort = prices[0].toLong()
            curr[0] = 0
            for (i in 1..<n) {
                var res = curr[i - 1]
                res = max(res, prices[i] + bestLong)
                res = max(res, -prices[i] + bestShort)
                curr[i] = res
                bestLong = max(bestLong, prev[i - 1] - prices[i])
                bestShort = max(bestShort, prev[i - 1] + prices[i])
            }
            val tmp = prev
            prev = curr
            curr = tmp
        }
        return prev[n - 1]
    }
}