Maximum Subarray
Given an integer array nums[], find the subarray with the largest sum, and return its sum.
Input:
nums = [-2,1,-3,4,-1,2,1,-5,4]Output:
6Explanation:
The subarray [4,-1,2,1] has the largest sum 6.
This problem is about finding the maximum possible sum among all non-empty contiguous subarrays. The key idea is to scan from left to right and decide at each position whether you should extend the previous subarray or start a new subarray at the current element. If the running sum becomes negative, it can only hurt future sums, so you reset and restart. This leads to a linear-time solution commonly known as Kadane’s algorithm.