39. Best Window Total
A shop records its profit (or loss) for every day of a season, and the owner wants to find the best run of exactly k days in a row, meaning the k consecutive days whose profits add up to the largest total.
Write a method maxWindowSum that takes the array nums of daily profits and the integer k, and returns the largest possible sum of k consecutive elements of nums. A window of k days always fits, because k never exceeds the number of days.
Example 1
- Input:
- nums = [2,1,5,1,3,2], k = 3
- Output:
- 9
- Explanation:
The windows of 3 days sum to 8, 7, 9 and 6. The best is 5 + 1 + 3 = 9.
Example 2
- Input:
- nums = [4,4,4], k = 2
- Output:
- 8
- Explanation:
Every window of 2 days sums to 8.
Constraints
1 ≤ k ≤ nums.length ≤ 1000
-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.
Expected complexity
- Time
- O(n)
- Space
- O(1)