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 K INPUT nums array: 2 i=0 1 i=1 3 i=2 k = 10 Score Formula: score = sum × length Example: [1,2,3,4,5] (1+2+3+4+5) × 5 = 75 Subarrays to check: [2],[1],[3],[2,1],[1,3],[2,1,3] Total: 6 subarrays ALGORITHM (DP) 1 Init prefix sums prefix[i] = sum of nums[0..i] 2 Two pointers/Sliding Track valid window end 3 Check score < k sum(i,j) × len < k 4 Count valid subarrays Add count for each end Score Calculations: [2]: 2×1=2 <10 OK [1]: 1×1=1 <10 OK [3]: 3×1=3 <10 OK [2,1]: 3×2=6 <10 OK [1,3]: 4×2=8 <10 OK [2,1,3]: 6×3=18 FAIL Valid count: 5 FINAL RESULT Valid Subarrays (score < 10): [2] score=2 [1] score=1 [3] score=3 [2,1] score=6 [1,3] score=8 [2,1,3] score=18 Output: 5 Key Insight: Use sliding window with two pointers. For each right endpoint, find the leftmost valid left endpoint using binary search or expand/shrink window. Prefix sums enable O(1) range sum queries. The score constraint sum(i,j) × (j-i+1) < k helps prune invalid windows early. DP tracks cumulative counts efficiently. TutorialsPoint - Count Subarrays With Score Less Than K | Dynamic Programming Approach
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