Maximum Subarray medium
Problem Statement
Find the contiguous subarray within a one-dimensional array (containing at least one number) which has the largest sum and return its sum.
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
Steps and Explanation
This problem can be efficiently solved using Kadane's Algorithm. The core idea is to maintain a currentMax
variable that tracks the maximum sum ending at the current position. We also keep track of a globalMax
variable that stores the overall maximum sum encountered so far.
-
Initialization: Set both
currentMax
andglobalMax
to the first element of the array. -
Iteration: Iterate through the array starting from the second element.
-
Update
currentMax
: For each element, we decide whether to include it in the current subarray. If adding the current element tocurrentMax
results in a larger value, we updatecurrentMax
. Otherwise, we start a new subarray from the current element (settingcurrentMax
to the current element). -
Update
globalMax
: After updatingcurrentMax
, compare it withglobalMax
. IfcurrentMax
is greater, updateglobalMax
. -
Return
globalMax
: After iterating through the entire array,globalMax
will hold the maximum sum of any contiguous subarray.
Code (C#)
using System;
public class Solution {
public int MaxSubArray(int[] nums) {
if (nums == null || nums.Length == 0) {
return 0; // Handle empty input
}
int currentMax = nums[0];
int globalMax = nums[0];
for (int i = 1; i < nums.Length; i++) {
currentMax = Math.Max(nums[i], currentMax + nums[i]);
globalMax = Math.Max(globalMax, currentMax);
}
return globalMax;
}
}
Complexity Analysis
- Time Complexity: O(n), where n is the length of the input array. We iterate through the array once.
- Space Complexity: O(1). We use only a few constant extra variables. The algorithm is in-place.