Home > database >  i cant get the right result of the contiguous subarray of arr with the maximal sum of items
i cant get the right result of the contiguous subarray of arr with the maximal sum of items

Time:05-20

so i found a solution for this mathematical problem which is this one

function getMaxSubSum(arr) {
    let maxSum = 0;
    let partialSum = 0;
  
    for (let item of arr) { // for each item of arr
      partialSum  = item; // add it to partialSum
      maxSum = Math.max(maxSum, partialSum); // remember the maximum
      if (partialSum < 0) partialSum = 0; // zero if negative
    }
  
    return maxSum;
  }

  alert ( getMaxSubSum([1,-2,3,9,-9,6]) )

BUT i want to achieve it with another way and im trying this code

function kadane () {
    arr = [1,-2,3,9,-9,6]
    let  maxSub = maxGlobal = arr[0]
    for (i=3 ; i<arr.length-1; i   ) {
     maxSub = Math.max(arr[i], maxSub   arr[i])
       
    if (maxSub > maxGlobal) {
        maxSub = maxGlobal

       
    }

    
    
}
return  maxSub

}
alert (kadane())

does anyone know what im doing wrong?

CodePudding user response:

Your solution were really close !

Here you inverted maxSub and maxGlobal in the if section.

Also, I don't know why but your for loop where starting at 3 instead of 1.

Here is your working example

function kadane(arr) {
  let maxSub = arr[0]
  let maxGlobal = arr[0]
  for (i = 1; i < arr.length; i  ) {
    maxSub = Math.max(arr[i], maxSub   arr[i])
    if (maxSub > maxGlobal) {
      maxGlobal = maxSub
    }
  }
  return maxGlobal
}

const arr = [1, -2, 3, 9, -9, 6]
alert(kadane(arr))


A little more...

Also, note that you could also have checked the maximum of 2 numbers consecutively.

Example using Array#reduce

function kadane(arr) {
  return arr.reduce((acc, curr, index) => {
    if(index === 0) return curr > 0 ? curr : 0
    else {
      const sum = curr   arr[index-1]
      return sum > acc ? sum : acc
    }
  }, 0)
}

console.log(kadane([1, -2, 3, 9, -9, 6]))
console.log(kadane([-1, -2, -3, -4, -5, -6]))

  • Related