Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

53. 最大子数组和 #12

Open
heyLiup opened this issue May 14, 2022 · 0 comments
Open

53. 最大子数组和 #12

heyLiup opened this issue May 14, 2022 · 0 comments

Comments

@heyLiup
Copy link
Owner

heyLiup commented May 14, 2022

https://leetcode.cn/problems/maximum-subarray/

贪心

var maxSubArray = function (nums) {
  let preSum = nums[0];  // 上一次的和,如果大于等于0,就加
  let max = nums[0];
  for (let i = 1; i < nums.length; i++) {
    let curSum = nums[i];
    if (preSum >= 0) {
      curSum = curSum + preSum;
    }
    preSum = curSum;

    max = Math.max(max, curSum);
  }
  return max;
};

动态规划


var maxSubArray = function (nums) {
  for (let i = 1; i < nums.length; i++) {
    let pre = nums[i - 1];
    if (pre >= 0) {
      nums[i] = nums[i] + pre;
    }
  }
  return Math.max(...nums);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant