FrontendInterviews.dev

Loading problem…

107. Maximum Subarray - Best Period Analysis

Medium•
Acceptance: 93.33%
•
🔓3/3 Pro unlocks today

You're building an analytics dashboard that needs to find the best performing time period. Given daily profits or losses, find the contiguous subarray with the largest sum (Kadane's Algorithm).

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Requirements

1. Basic Functionality

  • Find contiguous subarray with maximum sum
  • Subarray must contain at least one element
  • Handle negative numbers
  • Return the sum, not the subarray

Example Usage

maxSubArray([-2,1,-3,4,-1,2,1,-5,4]); // 6
// Explanation: [4,-1,2,1] has the largest sum = 6

maxSubArray([1]); // 1
maxSubArray([5,4,-1,7,8]); // 23

Real-World Context

This problem models real analytics scenarios:

  • Profit analysis: Find best performing period
  • Stock prices: Maximum profit from price changes
  • Performance metrics: Best consecutive period
  • Revenue analysis: Best revenue period

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • Subarray must be contiguous
  • At least one element in subarray