-3

Given an integer array nums,

find the contiguous subarray (containing at least one number)

which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],

Output: 6

Explanation: [4,-1,2,1] has the largest sum = 6.

Inputs:[-1]

Output:-1

Inputs:[-2,-1]

Outputs:[-1]

What i try in my JS:

 
    var maxSubArray = function(nums) {
    result=0
    negativenumber=[]
    for(i=0;i<nums.length;i++){
        if(nums[i]<0){
            negativenumber.push(nums[i]);
    }else{
      result+=nums[i];
    }
    }
    return result;
};
maxSubArray([-2,1,-3,4,-1,2,1,-5,4])//should return 6
maxSubArray([-1])//should return -1
maxSubArray([-1,-2])//should return -1

1

1 Answer 1

3

You can use Kadane's algorithm.

function maxSum(arr){
  let a1 = 0
  let a2 = arr[0]
  arr.forEach((i) => {
    a1 = Math.max(i, a1 + i)
    a2 = Math.max(a2, a1)
  })
  return a2
}
console.log(maxSum([-2,1,-3,4,-1,2,1,-5,4]))
console.log(maxSum([-1]))
console.log(maxSum([-1,-2]))

Sign up to request clarification or add additional context in comments.

6 Comments

if i use [-1] the output should be -1.If you don't mind, could you fix some code to meet the request?
@Jacky Ok I updated
Sorry,my bad.I didn't fully said there is another request.If i use [-1,-2],the output should be -1.But your code's output is 0.Would you fix the code?
@Jacky I edited the code. Accept the answer if it helped
What's the purpose of the param a?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.