-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMax Subarray.py
92 lines (59 loc) · 2.04 KB
/
Max Subarray.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
"""
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Input:
[-2,1]
Output:
-1
Expected:
1
"""
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
numLength = len(nums)
x = 0
if numLength != 0:
highestScore = nums[0]
else:
return numLength
while x <= (numLength-1):
y = x
runningArray = []
while y <= (numLength-1):
if x == y:
runningTotal = nums[x]
runningArray.append(nums(x))
if nums[x] > highestScore:
# make x the highestScore
highestScore = nums[x]
# add x to the array
else:
runningTotal += nums[y]
runningArray.append(nums(y))
if runningTotal > highestScore:
# make x + y the highestScoreyz
highestScore = runningTotal
y += 1
x += 1
return highestScore
Answer = Solution()
"""
testArray = [-2,1,-3,4,-1,2,1,-5,4]
print("testArray =", testArray, "Largest sum = ", Answer.maxSubArray(testArray))
testArray = [-2,-3,-1,-5]
print("testArray =", testArray, "Largest sum = ", Answer.maxSubArray(testArray))
"""
testArray = [-2,1]
print("testArray =", testArray, "Largest sum = ", Answer.maxSubArray(testArray))
"""
testArray = []
print("testArray =", testArray, "Largest sum = ", Answer.maxSubArray(testArray))
"""