Problem Description
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Examples
Example 1: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Example 2: Input: nums = [1] Output: 1 Example 3: Input: nums = [5,4,-1,7,8] Output: 23
Python Solution
def maxSubArray(nums: List[int]) -> int:
curr_sum = max_sum = nums[0]
for num in nums[1:]:
curr_sum = max(num, curr_sum + num)
max_sum = max(max_sum, curr_sum)
return max_sum
Java Solution
class Solution {
public int maxSubArray(int[] nums) {
int currSum = nums[0];
int maxSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currSum = Math.max(nums[i], currSum + nums[i]);
maxSum = Math.max(maxSum, currSum);
}
return maxSum;
}
}
C++ Solution
class Solution {
public:
int maxSubArray(vector& nums) {
int currSum = nums[0];
int maxSum = nums[0];
for (int i = 1; i < nums.size(); i++) {
currSum = max(nums[i], currSum + nums[i]);
maxSum = max(maxSum, currSum);
}
return maxSum;
}
};
JavaScript Solution
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
let currSum = nums[0];
let maxSum = nums[0];
for (let i = 1; i < nums.length; i++) {
currSum = Math.max(nums[i], currSum + nums[i]);
maxSum = Math.max(maxSum, currSum);
}
return maxSum;
};
C# Solution
public class Solution {
public int MaxSubArray(int[] nums) {
int currSum = nums[0];
int maxSum = nums[0];
for (int i = 1; i < nums.Length; i++) {
currSum = Math.Max(nums[i], currSum + nums[i]);
maxSum = Math.Max(maxSum, currSum);
}
return maxSum;
}
}
Complexity Analysis
- Time Complexity: O(n) where n is the length of the array
- Space Complexity: O(1) as we only use two variables
Solution Explanation
This solution uses Kadane's Algorithm to find the maximum subarray sum. Here's how it works:
- Initialize variables:
- currSum: tracks current subarray sum
- maxSum: tracks maximum sum found
- For each number:
- Choose between starting new subarray or extending current one
- Update maxSum if current sum is larger
Key points:
- Uses Kadane's Algorithm
- Handles negative numbers
- Single pass through array
- Constant space complexity