Interview Questions/Coding/Best Profit Window With Limit

Best Profit Window With Limit

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Best Profit Window With Limit

An investment report stores monthly profit and loss values in chronological order. Positive values are gains and negative values are losses. You may choose any non-empty continuous block of months, but the block length cannot be greater than k. Return the maximum net profit possible from such a block.

Examples

Example 1
Input:
1 2 3 -2 5
3
Output:
6

Explanation: The best segment with length at most 3 is [1, 2, 3], whose sum is 6.

Approach hint

Use prefix sums so any segment sum can be written as prefix[right] - prefix[left].

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

solution.cpp