-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumSubarrayDay12.py
More file actions
55 lines (41 loc) · 1.2 KB
/
Copy pathMaximumSubarrayDay12.py
File metadata and controls
55 lines (41 loc) · 1.2 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
#Brute Force Approach
# class Solution:
# def maxSubArray(self, nums: List[int]) -> int:
# n = len(nums)
# max_sum = float('-inf')
#
# for i in range(n):
# for j in range(i, n):
# curr_sum = 0
# for k in range(i, j + 1):
# curr_sum += nums[k]
# max_sum = max(max_sum, curr_sum)
#
# return max_sum
# Time Complexity: O(n³)
# Space Complexity: O(1)
#Better Approach
# class Solution:
# def maxSubArray(self, nums: List[int]) -> int:
# n = len(nums)
# max_sum = float('-inf')
#
# for i in range(n):
# curr_sum = 0
# for j in range(i, n):
# curr_sum += nums[j]
# max_sum = max(max_sum, curr_sum)
# return max_sum
# Time Complexity: O(n²)
# Space Complexity: O(1)
#Optimal Approach:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
max_sum = nums[0]
curr_sum = nums[0]
for i in range(1, len(nums)):
curr_sum = max(nums[i], curr_sum + nums[i])
max_sum = max(max_sum, curr_sum)
return max_sum
# Time Complexity: O(n)
# Space Complexity:O(1)