Given an integer array nums, find the subarray with the largest sum, and return its sum.
currentSum = max(num, currentSum + num). maxSum = max(maxSum, currentSum). This gives O(n) time, O(1) space.A trading algorithm scanning daily returns needs to find the contiguous window of days that maximizes total portfolio gain. Kadane's algorithm runs this in O(n) — one pass over millions of data points. If the cumulative return dips negative, the algorithm resets its window, just like abandoning a losing streak and starting fresh. This single-pass efficiency is critical in high-frequency trading systems where every millisecond matters.
Kadane's algorithm maintains a running subarray sum. The key insight: if curSum ever goes negative, it can only hurt future sums — so we discard it and start fresh.
maxSum = nums[0] (handles all-negative arrays), curSum = 0.num in nums: if curSum < 0, reset curSum = 0.num to curSum.maxSum = max(maxSum, curSum).maxSum after the loop.By resetting curSum to 0 whenever it goes negative, we guarantee we're always starting fresh subarrays at the best possible position. This achieves O(n) with O(1) extra space.
Discussion
…