Algorithms & Data Structuresmedium
Count Subarrays with Score Below K
Given an array nums of positive integers and an integer k, the score of a subarray is (sum of its elements) × (its length). Count the non-empty contiguous subarrays whose score is strictly less than k.
nums = [2, 1, 4, 3, 5], k = 10 => 6
[2]=2, [1]=1, [4]=4, [3]=3, [5]=5, [2,1] = 3×2 = 6
([1,4] = 5×2 = 10 is not < 10)
nums = [1, 1, 1], k = 5 => 5
[1], [1], [1], [1,1], [1,1] ([1,1,1] = 3×3 = 9)n up to 10^5, values up to 10^5, k up to 10^15 — target O(n).
Follow-ups
- Why does a sliding window work here, and what breaks if nums can contain zeros or negatives?
- Reported from the same phone screen: LC 1235 Maximum Profit in Job Scheduling — sort by end time, DP with binary search over end times.