[英]Get Maximum Subarray with the array
I want to do a variation of the get Maximum subarray from leetcode in which I collect the entire maximum subarray as well, but I can't seem to figure out what I'm missing.我想对 leetcode 中的 get Maximum 子数组做一个变体,在其中我也收集了整个最大子数组,但我似乎无法弄清楚我缺少什么。
var maxSubArray = function(nums) {
let currSum = 0;
let maxSum = -Infinity;
let currArray = [];
let maxArray = [];
for (let i = 0; i < nums.length; i++) {
currSum += nums[i];
if (Math.max(currSum, maxSum) != maxSum) {
maxArray = currArray;
maxSum = currSum;
currArray.push(nums[i]);
}
maxSum = Math.max(currSum, maxSum);
if (currSum < 0) {
currSum = 0;
currArray = []
}
}
console.log(maxArray);
return maxSum;
};
I recognize why this is wrong, as the currSum value cannot have a negative component because it'd always be a lower sum than the current maxSum.我知道为什么这是错误的,因为 currSum 值不能有负分量,因为它总是比当前的 maxSum 低。 But I'm not sure what condition it would require for this.
但我不确定这需要什么条件。 I feel like I'm missing something obvious but cannot think of it :(
我觉得我错过了一些明显的东西,但想不起来:(
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
I was going about it the wrong way as I was storing an array when I could have just stored the index.当我本来可以存储索引时,我正在存储一个数组,所以我以错误的方式进行操作。
var maxSubArray = function(nums) {
let currSum = 0;
let maxSum = -Infinity;
let prevMax = -Infinity;
let start = 0;
let end = 0;
for (let i = 0; i < nums.length; i++) {
currSum += nums[i];
if (nums[i] > maxSum) {
start = i;
}
if (Math.max(currSum, maxSum) != maxSum) {
maxSum = currSum;
end = i;
}
if (currSum < 0) {
currSum = 0;
if (nums[i+1] != undefined) {
start = i+1;
}
}
}
console.log(start, end);
console.log(nums.slice(start, end+1))
return maxSum;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.