-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargestsum.py
More file actions
67 lines (55 loc) · 1.42 KB
/
largestsum.py
File metadata and controls
67 lines (55 loc) · 1.42 KB
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
import math
import random
'''
Given an integer array, find its contiguous subarray with maximum sum.
Input: An array of 𝑛 integer numbers (𝑎[0],…,𝑎[𝑛−1])
Output: The maximum value of the sum 𝑎[𝑙] +⋯+ 𝑎[𝑟] among all possible intervals [𝑙,𝑟] with 0 <= 𝑙<=𝑟<=𝑛−1.
Note that the brute force way is to calculate the following sums and keep track of the max is as follows:
a[0]
a[0] + a[1]
a[0] + a[1] + a[2]
...
a[0] + a[1] + ... + a[n-1]
a[1]
a[1] + a[2]
a[1] + a[2] + a[3]
...
a[1] + ... + a[n-1]
a[2]
a[2] + a[3]
a[2] + a[3] + ... + a[n-1]
...
a[n-1]
'''
def max_sum(a):
current_max = float('-inf')
current_max_range = []
n = len(a)
for l in range (0, n):
for r in range (0, n):
sum = 0
max_range = []
for k in range(l,r + 1):
max_range.append(k)
sum += a[k]
if sum > current_max:
current_max = sum
current_max_range = max_range
return current_max, current_max_range
N = 10
a= []
for i in range (0, N):
num = random.randint(-100, 100)
a.append(num)
print(a)
maxsum, maxsumrange = max_sum(a)
print ("max sum is ", maxsum)
print ("The range is:")
print(maxsumrange)
'''
Output from one of my tests:
[-96, 99, -12, 48, -26, -6, -19, -44, -99, 42]
max sum is 135
The range is:
[1, 2, 3]
'''