Maximum Subarray
Given an integer array nums, find the subarray with the largest sum and return its sum.
A subarray is a contiguous part of the array.
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:
4 + (-1) + 2 + 1 = 6
So the answer is 6.
Example 2
Input
nums = [5,4,-1,7,8]
Output
23
Explanation
The entire array gives the maximum sum:
5 + 4 - 1 + 7 + 8 = 23
Therefore, the answer is 23.
Constraints
Hints:
Hint 1
Keep track of the maximum sum of a subarray ending at the current position.
Hint 2
If the current subarray sum becomes worse than starting from the current element, start a new subarray.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 18, 2026
Last updated
Aug 18, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output