preface

It’s Friday again, is HXDM still writing bugs? Take a break and watch the nuggets!

Topic describes

53. Maximum suborder sum.

Given an integer array nums, find a contiguous subarray with the maximum sum (the subarray contains at least one element) and return the maximum sum.

Example 1:

Input: nums = [-- 2, 1, 3, 4, 1, 2, 1, 5, 4] output: 6: continuous subarray and maximum of [4, 1, 2, 1], is 6.Copy the code

Example 2:

Input: nums = [1] Output: 1Copy the code

Example 3:

Input: nums = [0] Output: 0Copy the code

Example 4:

Input: nums = [-1] Output: -1Copy the code

Example 5:

Input: nums = [-100000] Output: -100000Copy the code

Tip:

  • 1 <= nums.length <= 3 * 10^4
  • -10^5 <= nums[i] <= 10^5

Their thinking

If the previous term is greater than 0, then you add the current term to the previous term. Why use the previous term as a condition that the previous term is greater than 0? If it’s less than 0, then we skip to the next item, and we end up with a result array, and then we maximize the result array.

The problem solving code

var maxSubArray = function(nums) {
  const n = nums.length;
  for (let i = 1; i < n; i++) {
    if (nums[i-1] > 0) {
      nums[i] += nums[i-1]
    }
  }
  return Math.max.apply(this, nums)
}
Copy the code

Swipe questions and punch out records

Here is the previous swipe card records, you can have a look, if you have any different views and views or feel what is wrong, welcome to leave a message in the comment area! 🙏 🙏 🙏

[LeetCode0303 topic area and retrieval – array immutable] | punch brush

[LeetCode1200. Minimum absolute difference] | punch brush

[LeetCode0304 topic 2 d area and retrieval – matrix immutable] | punch brush

[LeetCode11 topic containers of most water] | punch brush

[LeetCode0338 topic bit count] | punch brush

[LeetCode209 topic length minimum subarray] | punch brush

[LeetCode236 topic in recent common ancestor of binary tree] | punch brush

[LeetCode141 topic circular linked list] | punch brush

conclusion

It is necessary to write more questions, do not be afraid to write bad, the process of writing is the process of review, it is easier to deepen their understanding.

Come on! HXDM!!!!!! 💪 💪 💪

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign