
Problem
Solution
Submissions
Maximum Subarray Sum
Certification: Advanced Level
Accuracy: 100%
Submissions: 2
Points: 10
Write a Python function that finds the contiguous subarray within a one-dimensional number array with the largest sum using Kadane's algorithm.
Example 1
- Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
- Output: 6
- Explanation:
- Step 1: Initialize variables for current sum and maximum sum to the first element.
- Step 2: Iterate through the array, updating the current sum at each step.
- Step 3: For each element, decide whether to extend the current subarray or start a new one.
- Step 4: The contiguous subarray [4, -1, 2, 1] has the largest sum = 6.
- Step 5: Return 6 as the maximum sum.
Example 2
- Input: [1, -2, 3, -2, 5]
- Output: 6
- Explanation:
- Step 1: Initialize variables for current sum and maximum sum.
- Step 2: Iterate through the array, maintaining a running sum.
- Step 3: Reset the current sum to zero if it becomes negative.
- Step 4: The contiguous subarray [3, -2, 5] has the largest sum = 6.
- Step 5: Return 6 as the maximum sum.
Constraints
- 1 ≤ len(nums) ≤ 10^5
- -10^4 ≤ nums[i] ≤ 10^4
- Time Complexity: O(n), where n is the length of the input array
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Initialize two variables: max_so_far = nums[0] and max_ending_here = nums[0]
- Iterate through the array starting from the second element
- For each element, update max_ending_here = max(nums[i], max_ending_here + nums[i])
- Update max_so_far = max(max_so_far, max_ending_here)
- The final value of max_so_far will be the maximum subarray sum
- Handle empty array as a special case