-
Notifications
You must be signed in to change notification settings - Fork 1
/
subarray_expected.py
96 lines (82 loc) · 2.72 KB
/
subarray_expected.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
import math, random
from collections import deque
# Problem: L is an array of integers. K is an integer (1 <= K <= len(L)).
# Find a subarray of L such that 1) the length of the subarray is equal to or
# larger than K, and 2) the sum of the elements in the subarray is maximized.
#
# For example, if L is [2, -1, -1, -1, 4, -1, 3, 1] and K=3, the subarray
# [4, -1, 3, 1] maximizes the sum and the sum is 7.
#
# Input: L and K
# Output: The maximum sum
# O(N^3) algorithm
def solve_n3(L, K):
N = len(L)
max_sum = -math.inf
for k in range(K, N + 1):
for i in range(0, N - k + 1):
sum = 0
for j in range(i, i + k):
sum += L[j]
max_sum = max(max_sum, sum)
return max_sum
# O(N^2) algorithm
def solve_n2(L, K):
N = len(L)
max_sum = -math.inf
for k in range(K, N + 1):
sum = 0
for i in range(0, k):
sum += L[i]
max_sum = max(max_sum, sum)
for i in range(0, N - k):
sum = sum - L[i] + L[i + k]
max_sum = max(max_sum, sum)
return max_sum
# O(N) algorithm
def solve_n(L, K):
# window = sum(L[0, ..., K-1])
window = 0
for i in range(K):
window += L[i]
max_overall = max_current = window
for i in range(K, len(L)):
# window = sum(L[i-K+1, ..., i])
window += L[i] - L[i - K]
# max_current = max(sum(a subarray whose last index is i))
max_current = max(window, max_current + L[i])
# max_overall tracks the max value of max_current.
max_overall = max(max_overall, max_current)
return max_overall
# For a given L and K, run the three algorithms (O(N^3), O(N^2) and O(N))
# and check that all the answers are equal.
def check_answers(L, K):
answer_n3 = solve_n3(L, K)
answer_n2 = solve_n2(L, K)
answer_n = solve_n(L, K)
if answer_n3 != answer_n2:
print(L, K)
print("Correct answer is %d but the O(N^2) algorithm answered %d" % (
answer_n3, answer_n2))
exit(0)
if answer_n3 != answer_n:
print(L, K)
print("Correct answer is %d but the O(N) algorithm answered %d" % (
answer_n3, answer_n))
exit(0)
# Run tests.
def run_tests():
# Add your test cases here.
check_answers([1, -1, -1, -1, 3, 2], 1)
check_answers([1, -1, -1, -1, 3, 2], 2)
check_answers([1, -1, -1, -1, 3, 2], 3)
check_answers([1, -1, -1, -1, 3, 2], 4)
# Generate many test cases and run.
for iteration in range(1000):
length = random.randint(1, 30)
L = [random.randint(-10, 10) for i in range(length)]
for K in range(1, length + 1):
check_answers(L, K)
print("All tests pass!")
if __name__ == "__main__":
run_tests()