CodeWars 5kyu. Maximum subarray sum
Return maximum sum of subarrays
The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:
maxSequence([-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.
Requirement
Should return maximum sum of any subarrays including empty list.
Return 0 when all of list’s element is negative numbers.
Solution
I used Dynamic Programming - Bottom up approach to solve this problem. Because I learned on some online lectures about Dynamic Programming recently.
First I catched that all the start and end element in subarray is positive numbers. So I decided to put all positive numbers’ index in positive_index list.
Make a 2 dementional array, sum[][] to keep the sum of subarrays.
Drew the recurrance Induction of this problem.
- Basis
- sum[i][i] = arr[positive_index[i]]
- sum[i][i+1] = arr[positive_index[i]] to arr[positive_index[j]] (i < positive_index.length - 1)
- Inductive Step
- sum[i][j] = sum[i][j-1] + sum[j-1][j] - arr[positive_index[j-1]]
- Basis
javaScript Solution
1 | var maxSequence = function(arr){ |
PPT slides
Made presentations for my algorithm study group