-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path53_maximum_subarray.py
More file actions
46 lines (32 loc) · 921 Bytes
/
53_maximum_subarray.py
File metadata and controls
46 lines (32 loc) · 921 Bytes
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
"""
---
title: Maximum subarray
number: 53
difficulty: medium
tags: ['Array','Divide and conquer','Dynamic programming']
solved: true
---
"""
"""
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
"""
from typing import List
"""
Largest sum contiguous subarray - Kadane's algorithm
"""
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
return self.simple(nums)
def simple(self,nums:List[int]):
max_sum = nums[0]
current_sum = 0
for number in nums:
if current_sum <0:
current_sum = 0
current_sum+=number
max_sum = max(max_sum,current_sum)
return max_sum
if __name__ == '__main__':
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(Solution().maxSubArray(nums))