← Questions
Sum of the longest run of positive numbers
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Microsoft's technical phone screen, last asked Jul 2025. It tests arrays and two pointers.
An integer array holds positive numbers, negative numbers and zeros. Find the longest contiguous run made only of positive numbers (strictly greater than 0) and return its sum. If several runs share the longest length, return the largest sum among them. If there are no positive numbers, return 0.
Interface
Unless you agree on a different interface with the interviewer, assume:
longest_positive_run_sum(nums: list[int]) -> int
Example
[1, 2, -1, 3, 4, 5, -2, 6] -> 12 # runs [1,2], [3,4,5], [6]; the longest sums to 12
[3, 4, -1, 10, 20] -> 30 # two runs of length 2; the larger sum wins
[-1, -2, -3] -> 0
[2, 0, 5] -> 5 # zero breaks a run; both runs have length 1
Constraints
-
0 <= len(nums) <= 10^5. -
-10^9 <= nums[i] <= 10^9; sums can exceed 32 bits.
Clarifying questions
- Is zero positive, or does it break a run?
- How should ties in length be broken?
- What should an empty array return?
What a strong answer covers
- One left-to-right pass keeping the current run's length and sum, reset on any non-positive value.
- The best answer kept as a
(length, sum)pair, updated when the run is longer, or equally long with a larger sum. - Updating the best at each step, or after the loop, so a run that ends the array is counted.
- O(n) time, O(1) space; 64-bit sums.
- Tests: no positives, the whole array positive, a tie on length, a zero inside a run.
Follow-ups
- Return the run's start and end indices as well.
- Return the maximum sum over all positive runs regardless of length.
- Allow one non-positive number inside a run.
Where it's asked
- Microsoft · Technical phone screen · Last asked Jul 202560 min · One technical round
What it tests
arrays · two pointers
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
