CodeWars 5kyu Maximum subarray sum

CodeWars 5kyu Maximum subarray sum

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

  1. Should return maximum sum of any subarrays including empty list.

  2. 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.

  1. 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.

  2. Make a 2 dementional array, sum[][] to keep the sum of subarrays.

  3. 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]]

javaScript Solution

Submit

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
var maxSequence = function(arr){
var positive_index = []

arr.filter(function positive_check(element, index){
if(element>0){
positive_index.push(index);
}
})

if (positive_index.length == 0) return 0;

var sum = Array(positive_index.length).fill(null).map(() => Array(positive_index.length));
var max = Number.MIN_SAFE_INTEGER;

for(var i=0; i<positive_index.length; i++){
sum[i][i] = arr[positive_index[i]];
if(max < sum[i][i]){
max = sum[i][i];
}
if(i+1<positive_index.length){
sum[i][i+1] = arr.slice(positive_index[i], positive_index[i+1]+1).reduce((a,b)=>a+b);
if(max < sum[i][i+1]){
max = sum[i][i+1];
}
}
}

for(var i=0; i< positive_index.length; i++){
for(var j=i+2; j< positive_index.length; j++){
sum[i][j] = sum[i][j-1] + sum[j-1][j] - arr[positive_index[j-1]];
if(max < sum[i][j]){
max = sum[i][j];
}
}
}
return max;
}

PPT slides

Made presentations for my algorithm study group

슬라이드1
슬라이드2
슬라이드3
슬라이드4
슬라이드5
슬라이드6
슬라이드7
슬라이드8
슬라이드9
슬라이드10
슬라이드11
슬라이드12
슬라이드13
슬라이드14
슬라이드15

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×