Untitled

 avatar
unknown
plain_text
a month ago
1.3 kB
1
Indexable
public class SubarrayScore {
    public long countSubarrays(int[] nums, long k) {
        long count = 0; // Total count of valid subarrays
        long sum = 0;   // Running sum of the current window
        int i = 0;      // Left pointer of the sliding window
        int j = 0;      // Right pointer of the sliding window

        while (j < nums.length) {
            sum += nums[j]; // Add the current element to the window sum

            // Calculate score using sum and window length
            long score = sum * (j - i + 1);

            // Shrink the window if the score exceeds k
            while (score >= k) {
                sum -= nums[i];
                i++; // Move the left pointer
                score = sum * (j - i + 1); // Recalculate the score
            }

            // Count all valid subarrays ending at j
            count += (j - i + 1);

            // Move the right pointer
            j++;
        }

        return count;
    }

    public static void main(String[] args) {
        SubarrayScore solution = new SubarrayScore();
        System.out.println(solution.countSubarrays(new int[]{2, 1, 4, 3, 5}, 10)); // Output: 6
        System.out.println(solution.countSubarrays(new int[]{1, 1, 1}, 5)); // Output: 5
    }
}
Leave a Comment