Leetcode刷题(第53题)——最大子数组和

x33g5p2x  于2022-03-01 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(281)

一、题目描述

  1. 给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。子数组 是数组中的一个连续部分。

二、示例

  1. 示例一
  2. 输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
  3. 输出:6
  4. 解释:连续子数组 [4,-1,2,1] 的和最大,为 6
  5. 示例二
  6. 输入:nums = [1]
  7. 输出:1
  8. 示例三
  9. 输入:nums = [5,4,-1,7,8]
  10. 输出:23

三、解题思路

  1. 这里我们以数组[-2, 1, -3, 4, -1, 2, 1, -5, 4]为例,因为这个要求是连续的数组。
  2. 当数组[-2],max = -2
  3. 当数组为[-2, 1] max = 1 //因为之前的max + current < currrent,所以我们将之前的删除。所以此时数组为[1]
  4. 当数组为[1, -3]时 max = -3 //因为 max + current = -2 > current = -3,所以当前数组为[1,-3]
  5. 当数组为[1, -3, 4]时,max = 4. //因为max + current = 2 < current = 4,所以当前的数组为[4]
  6. 当数组为[4, -1]时, max = 3 //因为 max + current = 3 > current = -1,所以当前数组为[4, -1]
  7. 当数组为[4, -1, 2]是,max = 5//因为max + current = 3 + 2 = 5 > current = 2,所以当前数组为[4, -1, 2]
  8. 当数组为[4,-1,2,1]时,max = 6//因为max +current = 5 + 1 = 6 > current = 1,所以当前数组为[4, -1,2, 1]
  9. 当数组为[4,-1,2,1,-5]时,max = 1, //因为max + current = 6- 5 = 1 > current = -5,所以当前数组为[4,-1,2,1,-5].
  10. 当数组为[4,-1,2,1,-5,4]时,max = 5,//因为max + current = 1 + 4 = 5 > current = 4,所以当前数组为[4,-1,2, 1, -5, 4]

如上述代码所示,此时最大值为[4,-1, 2, 1],此时我们应该使用一个变量来保存每次最大值。
四、代码展示

  1. /**
  2. * @param {number[]} nums
  3. * @return {number}
  4. */
  5. var maxSubArray = function(nums) {
  6. let result = nums[0]
  7. let max = nums[0]
  8. let current = nums[0]
  9. for(let i = 1; i < nums.length; i++) {
  10. current = nums[i]
  11. max = Math.max(max + current, current)
  12. result = Math.max(max, result)
  13. }
  14. return result
  15. };

五、结果

相关文章