본문 바로가기
나는 이렇게 학습한다/Algorithm & SQL

Maximum subarray sum

by daco2020 2022. 8. 12.

The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:

max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
# should be 6: [4, -1, 2, 1]

Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.

Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.

 

 

Solution:

def max_sequence(arr):
    value = [sum(arr[i:j+1]) for i in range(len(arr)) for j in range(len(arr))]
    return value and max(value) or 0

 

 

 

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

Give me a Diamond  (0) 2022.08.14
Consecutive strings  (0) 2022.08.13
List Filtering  (0) 2022.08.11
Sum of a sequence  (0) 2022.08.10
Remove anchor from URL  (0) 2022.08.09