滑动窗口

给定数组中的连续子数组,使其和达到最大值,并记录该子数组的起始和结束索引。最后,将最大和及其起始和结束索引存储在数组当中。

const arr = [-1,-2,3,9,-4,8];

let max = null;
let sum = null;

let i=0,j=0;

let length = arr.length;

if(max === null || sum === null){
  max = arr[0];
  sum = 0;
}
let indexList = [];

while(i<length){
  sum = 0;
  for(j=i;j<length;j++){
    sum += arr[j];
    if(sum >= max){
      max = sum;
      indexList.push({max,i,j});
    }
  }
  i++;
}


console.log(indexList);
console.log(max

滑动窗口之三数之和

04-27 00:47