Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from typing import List


class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
n = len(prices)
if n == 0 or k == 0:
return 0

if k >= n // 2:
return sum(
max(prices[i + 1] - prices[i], 0) for i in range(n - 1)
)

buy = [float('-inf')] * (k + 1)
sell = [0] * (k + 1)

for price in prices:
for j in range(1, k + 1):
buy[j] = max(buy[j], sell[j - 1] - price)
sell[j] = max(sell[j], buy[j] + price)

return sell[k]
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
function maxProfitIV(k: number, prices: number[]): number {
const n = prices.length;
if (n === 0 || k === 0) return 0;

if (k >= Math.floor(n / 2)) {
let profit = 0;
for (let i = 1; i < n; i++) {
if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
}
return profit;
}

const buy: number[] = new Array(k + 1).fill(-Infinity);
const sell: number[] = new Array(k + 1).fill(0);

for (const price of prices) {
for (let j = 1; j <= k; j++) {
buy[j] = Math.max(buy[j], sell[j - 1] - price);
sell[j] = Math.max(sell[j], buy[j] + price);
}
}

return sell[k];
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import unittest
from src.my_project.interviews.top_150_questions_round_22\
.ex_144_best_time_to_buy_stock_iv import Solution


class BestTimeToBuyStockIVTestCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()

def test_example_1(self):
self.assertEqual(2, self.solution.maxProfit(2, [2, 4, 1]))

def test_example_2(self):
self.assertEqual(7, self.solution.maxProfit(2, [3, 2, 6, 5, 0, 3]))

def test_single_price(self):
self.assertEqual(0, self.solution.maxProfit(1, [5]))

def test_no_profit(self):
self.assertEqual(0, self.solution.maxProfit(2, [5, 4, 3, 2, 1]))

def test_k_exceeds_half_n(self):
self.assertEqual(7, self.solution.maxProfit(10, [1, 3, 2, 5, 4, 6]))


if __name__ == '__main__':
unittest.main()
Loading