-
Notifications
You must be signed in to change notification settings - Fork 0
/
130.py
77 lines (65 loc) · 2.16 KB
/
130.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Problem:
Given an array of numbers representing the stock prices of a company in chronological
order and an integer k, return the maximum profit you can make from k buys and sells.
You must buy the stock before you can sell it, and you must sell the stock before you
can buy it again.
For example, given k = 2 and the array [5, 2, 4, 0, 1], you should return 3.
"""
from typing import List
def get_max_profit_helper(
arr: List[int],
curr_index: int,
curr_profit: int,
buys_left: int,
sells_left: int,
length: int,
) -> int:
# if the end of the array is reached or no more sells can be performed current
# profit is returned (base case for recursion)
if curr_index == length or sells_left == 0:
return curr_profit
# if the number of 'buys' and 'sells' left are equal, the stock needs to be bought
if buys_left == sells_left:
return max(
# wait for a different deal
get_max_profit_helper(
arr, curr_index + 1, curr_profit, buys_left, sells_left, length
),
# buy at the current price
get_max_profit_helper(
arr,
curr_index + 1,
curr_profit - arr[curr_index],
buys_left - 1,
sells_left,
length,
),
)
# if the number of 'buys' and 'sells' left are inequal, the stock needs to be sold
return max(
# wait and hold for selling at a different price
get_max_profit_helper(
arr, curr_index + 1, curr_profit, buys_left, sells_left, length,
),
# sell at the current price
get_max_profit_helper(
arr,
curr_index + 1,
curr_profit + arr[curr_index],
buys_left,
sells_left - 1,
length,
),
)
def get_max_profit(arr: List[int], k: int) -> int:
return get_max_profit_helper(arr, 0, 0, k, k, len(arr))
if __name__ == "__main__":
print(get_max_profit([5, 2, 4, 0, 1], 2))
print(get_max_profit([5, 2, 4], 2))
print(get_max_profit([5, 2, 4], 1))
"""
SPECS:
TIME COMPLEXITY: O(2 ^ n)
SPACE COMPLEXITY: O(n)
"""