Given an integer array nums, find the subarray with the largest sum, and return its sum.

By | 1 month ago

interviewjobsjavascriptkeralaitcareerskochitrivandrum

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The subarray [4,-1,2,1] has the largest sum 6.

Example 2:

Input: nums = [1] Output: 1 Explanation: The subarray [1] has the largest sum 1.

Example 3:

Input: nums = [5,4,-1,7,8] Output: 23 Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

Constraints:

1 <= nums.length <= 105
-104 <= nums[i] <= 104

To solve this problem in JavaScript, you can use a similar approach to the one used in Python, utilizing Kadane's algorithm. Here's how you can implement the solution to find the maximum subarray sum in JavaScript:

function maxSubarraySum(nums) { let maxSum = nums[0]; let currentSum = nums[0]; for (let i = 1; i < nums.length; i++) { currentSum = Math.max(nums[i], currentSum + nums[i]); maxSum = Math.max(maxSum, currentSum); } return maxSum; } // Test the function with the provided examples const example1 = [-2, 1, -3, 4, -1, 2, 1, -5, 4]; const example2 = [1]; const example3 = [5, 4, -1, 7, 8]; console.log(maxSubarraySum(example1)); // Output: 6 console.log(maxSubarraySum(example2)); // Output: 1 console.log(maxSubarraySum(example3)); // Output: 23

In this JavaScript function, `maxSubarraySum, we iterate through the array while maintaining two variables: currentSum` (which stores the maximum sum of the subarray ending at the current index) and `maxSum` (which stores the maximum sum found so far). At each step, `currentSum` is updated to be the maximum of the current element and the sum of the current element with the `currentSum. Then, maxSum` is updated if `currentSum` is greater than `maxSum. The final maxSum` is the largest sum of any subarray.