【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

尾語

還是要多多刷題,保持自己的一些思維習慣吧,加油!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章