Compute sum of longest positive subarray
Company: Microsoft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: Compute sum of longest positive subarray evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= len(nums) <= 10^5
- -10^9 <= nums[i] <= 10^9
- A 'positive' number is strictly > 0; zero breaks a run.
- Return 0 when there are no positive numbers (including the empty array).
- On a length tie, return the maximum sum among the longest runs.
Examples
Input: [1, 2, -1, 3, 4, 5, -2, 6]
Expected Output: 12
Explanation: Positive runs: [1,2] (len 2), [3,4,5] (len 3), [6] (len 1). Longest is [3,4,5] -> 3+4+5 = 12.
Input: [-1, -2, -3]
Expected Output: 0
Explanation: No positive numbers, so the answer is 0.
Input: []
Expected Output: 0
Explanation: Empty array has no positive run; return 0.
Input: [5]
Expected Output: 5
Explanation: A single positive element forms the only (and longest) run, sum 5.
Input: [1, 2, 3, -1, 4, 5, 6]
Expected Output: 15
Explanation: Both [1,2,3] and [4,5,6] have length 3; the larger sum is 4+5+6 = 15.
Input: [3, 4, -1, 10, 20]
Expected Output: 30
Explanation: Tie on length (both len 2): [3,4]=7 vs [10,20]=30. Return the max sum, 30.
Input: [0, 1, 0, 2, 0, 3]
Expected Output: 3
Explanation: Zeros are not positive and break runs, so every run has length 1: [1],[2],[3]. Among the longest, the max sum is 3.
Input: [-5, 7, -8, 7, 7]
Expected Output: 14
Explanation: Runs are [7] (len 1, sum 7) and [7,7] (len 2, sum 14). The longer run wins regardless of sum comparison -> 14.
Hints
- Scan left to right. Whenever you see a positive number, extend the current run (length += 1, sum += value); on any non-positive number, reset the current run to empty.
- Track the best answer as a (length, sum) pair. Update it when the current run is strictly longer, OR when it ties the best length but has a larger sum — that handles the tie-breaking rule.
- Initialize best length and best sum to 0 so that an array with no positives naturally returns 0 without a special case.