Count Subarrays With Score Less Than K
Problem Statement
The score of an array is its sum multiplied by its length. For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) × 5 = 75.
You are given an array of positive integers nums and an integer k. Count how many non-empty contiguous subarrays have a score strictly less than k.
An integer array nums (every element ≥ 1) and a 64-bit integer k.
The number of subarrays with score < k (as a 64-bit integer).
The subarrays [2], [1], [4], [3], [5] and [2, 1] (score 3 × 2 = 6) are below 10. For example [2, 1, 4] scores 7 × 3 = 21, which is too big.
Every subarray except [1, 1, 1] (score 3 × 3 = 9) has a score below 5: three single 1's (score 1) and two [1, 1]'s (score 4).
- • 1 ≤ nums.length ≤ 10^5
- • 1 ≤ nums[i] ≤ 10^5
- • 1 ≤ k ≤ 10^15
- • A sum can reach 10^10 and a score 10^15; the answer can reach 5·10^9. Use long long everywhere.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each start, extend right with a running sum until the score reaches k
For each right end, binary search the smallest start with score < k
Keep the longest window ending at right with score < k; add its length
Fix a start, grow the end, keep a running sum. The score is sum × length. Count each subarray while its score is below k, and stop at the first one that is not: from there the score only grows.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.