-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmaximum-score-from-performing-multiplication-operations.py
241 lines (226 loc) · 7.68 KB
/
maximum-score-from-performing-multiplication-operations.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# 1770. Maximum Score from Performing Multiplication Operations
# 🟠 Medium
#
# https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/
#
# Tags: Array - Dynamic Programming
import timeit
from functools import cache
from typing import List
# 1 call
# » Recursive 2.01183 seconds
# » MemoizedRecursive 0.00018 seconds
# The brute force solution is to recursively explore all possibilities.
#
# Time complexity: O(2^m) - Where m is the length of the multiplier
# array and it is bounded to 1000.
# Space complexity: O(m) - The height of the call stack will equal the
# size of the multiplier array, maxing out at 1000.
#
# This solution would probably fail with Time Limit Exceeded.
#
# This implementation is the same as the Memoized version removing
# the caching mechanism.
# We can reduce the time complexity if we cache intermediate results
# taking into account the left and right-most elements that we have
# already used.
#
# Time complexity: O(m^2) - We calculate the result of each 2 values of
# left and right pointers once and keep the max, both values can vary in
# the range 0..m.
# Space complexity: O(m) - The height of the call stack will equal the
# size of the multiplier array, maxing out at 1000.
#
# This solution fails with Time Limit Exceeded.
class MemoizedRecursive:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
# Define a recursive function that returns the maximum score
# that can be obtained from a portion of the input.
@cache
def dfs(l: int, r: int) -> int:
# Compute the current index we are accessing in the
# multipliers array.
idx = l + (len(nums) - r - 1)
# Base case, this is the last value in multipliers.
if idx == len(multipliers) - 1:
# Take the best of the two available options.
return max(
multipliers[idx] * nums[l], multipliers[idx] * nums[r]
)
else:
# Return the best of the two possible branch results.
return max(
multipliers[idx] * nums[l] + dfs(l + 1, r),
multipliers[idx] * nums[r] + dfs(l, r - 1),
)
# Initial call.
return dfs(0, len(nums) - 1)
# The iterative bottom-up approach is to compute intermediate results
# starting at the left of multipliers and saving them into a 2D array
# or a tuple-indexed dictionary.
#
# Time complexity: O(m^2) - We iterate over the pairs (0..m, 0..m)
# Space complexity: O(m^2) - The dictionary can grow to size O(m^2)
#
# Runtime: 6825 ms, faster than 72.67%
# Memory Usage: 124.1 MB, less than 5.05%
class BottomUpDP:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
# Store the best result found.
res = float("-inf")
# Use a dictionary to save intermediate results. Keys are tuples
# (i, j) of the best result possible for combinations of having
# the first i positions from the left and the first j positions
# from the right.
dp = {(0, 0): 0}
# Iterate over the range 1..len(multipliers)
for idx in range(len(multipliers)):
mul = multipliers[idx]
# Iterate over all the possibilities of the next dp position.
for i in range(idx + 2):
j = idx + 1 - i
# The optimal solution for this subproblem is the best
# between the optimal solution to the i-1 subproblem
# picking the left element or the j+1 solution picking
# the right element.
dp[(i, j)] = max(
dp[(i - 1, j)] + mul * nums[i - 1] if i else float("-inf"),
dp[(i, j - 1)] + mul * nums[-j] if j else float("-inf"),
)
# When on the last external loop update the best result.
if idx == len(multipliers) - 1 and dp[(i, j)] > res:
res = dp[(i, j)]
return res
# We can optimize the space complexity of the previous algorithm once
# we realize that we ever only need a maximum of m precomputed values
# to calculate the next row.
# TODO:- fix this solution, currently is not working, indexing nums is wrong.
class BottomUpDPOptimized:
def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:
# The dynamic programming intermediate results.
dp = [0] * len(multipliers)
# Iterate over the number of operations we have to perform.
for ops in range(len(multipliers)):
# Make a copy of dp.
last = dp.copy()
mul = multipliers[ops]
# Iterate over all the possibilities of the next dp position.
for i in range(ops + 2):
if not i:
dp[i] = last[i] + mul * nums[i + ops]
elif i == ops + 1:
dp[i] = last[i - 1] + mul * nums[ops - i]
else:
dp[i] = max(
last[i] + mul * nums[i + ops],
last[i - 1] + mul * nums[ops - i],
)
return dp[0]
def test():
executors = [
MemoizedRecursive,
BottomUpDP,
# BottomUpDPOptimized,
]
tests = [
# [[1], [1], 1],
# [[1, 2, 3], [3, 2, 1], 14],
[[-5, -3, -3, -2, 7, 1], [-10, -5, 3, 4, 6], 102],
[
[
555,
526,
732,
182,
43,
-537,
-434,
-233,
-947,
968,
-250,
-10,
470,
-867,
-809,
-987,
120,
607,
-700,
25,
-349,
-657,
349,
-75,
-936,
-473,
615,
691,
-261,
-517,
-867,
527,
782,
939,
-465,
12,
988,
-78,
-990,
504,
-358,
491,
805,
756,
-218,
513,
-928,
579,
678,
10,
],
[
783,
911,
820,
37,
466,
-251,
286,
-74,
-899,
586,
792,
-643,
-969,
-267,
121,
-656,
381,
871,
762,
-355,
721,
753,
-521,
],
6861161,
],
]
for executor in executors:
start = timeit.default_timer()
for _ in range(1):
for col, t in enumerate(tests):
sol = executor()
result = sol.maximumScore(t[0], t[1])
exp = t[2]
assert result == exp, (
f"\033[93m» {result} <> {exp}\033[91m for"
+ f" test {col} using \033[1m{executor.__name__}"
)
stop = timeit.default_timer()
used = str(round(stop - start, 5))
cols = "{0:20}{1:10}{2:10}"
res = cols.format(executor.__name__, used, "seconds")
print(f"\033[92m» {res}\033[0m")
test()