1286. Few Negatives Best Sum

A shop records the profit or loss of every day in the array nums. A day with a negative value is a loss day, and a day with value zero is not a loss day. The manager wants the best stretch of consecutive days to showcase, but the stretch may contain at most k loss days.

Return the largest sum of a non-empty contiguous subarray of nums that contains at most k negative numbers, as a 64-bit integer. Because k is at least 1, a single day is always allowed, so an answer always exists. With up to 200000 days, aim for O(n) time and O(n) extra space using prefix sums and a monotonic deque.

Example 1

Input:
nums = [4,-2,5,-3,6], k = 1
Output:
8
Explanation:

The stretch (5, -3, 6) has one negative value and sums to 8; the whole array has two negatives, so it is not allowed.

Example 2

Input:
nums = [-5,-2,-9], k = 1
Output:
-2
Explanation:

Every stretch must be non-empty and all values are negative, so the best is the single element -2.

Example 3

Input:
nums = [3,-1,2,-1,3], k = 2
Output:
6
Explanation:

The whole array has exactly two negatives, which is allowed, and its sum is 6.

Constraints

  • 1 ≤ n ≤ 2 * 105, where n is the length of nums
  • 1 ≤ k ≤ n
  • -104 ≤ nums[i] ≤ 104

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…