LeetCode in Kotlin

2302. Count Subarrays With Score Less Than K

Hard

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

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.

Example 1:

Input: nums = [2,1,4,3,5], k = 10

Output: 6

Explanation:

The 6 subarrays having scores less than 10 are:

Note that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.

Example 2:

Input: nums = [1,1,1], k = 5

Output: 5

Explanation:

Every subarray except [1,1,1] has a score less than 5.

[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.

Thus, there are 5 subarrays having scores less than 5.

Constraints:

Solution

class Solution {
    fun countSubarrays(nums: IntArray, k: Long): Long {
        var sum: Long = 0
        var count: Long = 0
        var i = 0
        var j = 0
        while (i < nums.size) {
            sum += nums[i].toLong()
            while (sum * (i - j + 1) >= k) {
                sum -= nums[j++].toLong()
            }
            count += (i++ - j + 1).toLong()
        }
        return count
    }
}