Skip to content

2302. Count Subarrays With Score Less Than K #1617

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to count the number of non-empty subarrays of a given array whose score (defined as the product of the subarray's sum and its length) is strictly less than a given integer k. Given the constraints, an efficient approach is necessary to avoid a brute-force solution.

Approach

The key insight here is that for a given starting index i, the score of the subarray starting at i and ending at j increases as j increases. This allows us to use a binary search approach to efficiently determine the maximum valid j for each starting index i.

  1. Prefix Sum Array: Compute a prefix sum array to quickly calculate the sum of any subarray.
  2. Binary Search: For each starting index i, use binary search to…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Apr 28, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Apr 28, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested hard Difficulty
2 participants