Count Subarrays With Score Less Than K - Problem

The score of an array is defined as the product of its sum and its length.

For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) × 5 = 75.

Given a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k.

A subarray is a contiguous sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3], k = 10
Output: 5
💡 Note: Subarrays: [2] score=2×1=2<10 ✓, [2,1] score=3×2=6<10 ✓, [2,1,3] score=6×3=18≥10 ✗, [1] score=1×1=1<10 ✓, [1,3] score=4×2=8<10 ✓, [3] score=3×1=3<10 ✓. Total: 5 valid subarrays.
Example 2 — Small K Value
$ Input: nums = [1,1,1], k = 5
Output: 5
💡 Note: Subarrays: [1] score=1×1=1<5 ✓, [1,1] score=2×2=4<5 ✓, [1,1,1] score=3×3=9≥5 ✗, [1] score=1×1=1<5 ✓, [1,1] score=2×2=4<5 ✓, [1] score=1×1=1<5 ✓. Total: 5 valid subarrays.
Example 3 — Large K Value
$ Input: nums = [1,2], k = 100
Output: 3
💡 Note: All subarrays have score < 100: [1] score=1×1=1<100 ✓, [1,2] score=3×2=6<100 ✓, [2] score=2×1=2<100 ✓. Total: 3 valid subarrays.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105
  • 1 ≤ k ≤ 1015

Visualization

Tap to expand
Count Subarrays With Score Less Than K213nums = [2,1,3], k = 10[2]: sum=2, len=1, score=2×1=2 < 10 ✓[2,1]: sum=3, len=2, score=3×2=6 < 10 ✓[2,1,3]: sum=6, len=3, score=6×3=18 ≥ 10 ✗[1]: sum=1, len=1, score=1×1=1 < 10 ✓[1,3]: sum=4, len=2, score=4×2=8 < 10 ✓[3]: sum=3, len=1, score=3×1=3 < 10 ✓Answer: 5 subarrays have score < 10
Understanding the Visualization
1
Input
Array nums=[2,1,3] and threshold k=10
2
Calculate Scores
For each subarray: score = sum × length
3
Count Valid
Count subarrays where score < k
Key Takeaway
🎯 Key Insight: Score grows faster than linearly due to multiplication by length, enabling early termination optimization
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen