【codewars】Maximum subarray sum【求最大子序列的和】

题目

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.

思路

刚开始拿到这个题目,没想到思路,只想到了暴力求解的方式,但是自己也想不到最优解的思路,于是只能去solutions里面看别人的。
看了别人代码,思路还是没理解,去网上找了别人讲解的帖子,进行的参考,如下:

要点是若一段子数组arr[i]-arr[j]之和为负数,则以这段数组的下一个元素arr[j + 1]为终点的最大子数组之和必然为arr[j + 1]本身

用到两个辅助变量:maxTempmaxResmaxTemp表示:本次循环之后数组的最大子序列的和;maxRes表示:数组arr的最大子序列的和,即题目所求。

for循环遍历数组arr,每次取到一个元素后,加到maxTemp中,然后判断maxTemp,若小于0,则将maxTemp设置为0,否则不变。然后去maxTempmaxRes的最大值赋给maxRes用于返回。

代码实现(JS)

var maxSequence = function(arr){
  // ...
  if(arr.length == 0){
    return 0;
  }

  var maxTemp = 0;
  var maxRes = 0;
  for(var k of arr){
    maxTemp += k;
    if(maxTemp <0){
      maxTemp = 0;
    }
    maxRes = maxRes >= maxTemp? maxRes : maxTemp;
  }

  return maxRes;
}

参考资料

  1. https://www.jianshu.com/p/4edab8dbea9f

尾语

还是要多多刷题,保持自己的一些思维习惯吧,加油!

你可能感兴趣的:(Javascript,codewars)