← All problems

3254. Find the Power of K Size Subarrays I

MediumOpen on LeetCodeProblem statement

Problem Statement

3254. Find the Power of K-Size Subarrays I

Medium


You are given an array of integers nums of length n and a positive integer k.

The power of an array is defined as:

You need to find the power of all subarrays of nums of size k.

Return an integer array results of size n - k + 1, where results[i] is the power of nums[i..(i + k - 1)].

 

Example 1:

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

Output: [3,4,-1,-1,-1]

Explanation:

There are 5 subarrays of nums of size 3:

Example 2:

Input: nums = [2,2,2,2,2], k = 4

Output: [-1,-1]

Example 3:

Input: nums = [3,2,3,2,3,2], k = 2

Output: [-1,3,-1,3,-1]

 

Constraints:

Java

Source file
class Solution {
    public int[] resultsArray(int[] nums, int k) {
        int n = nums.length, rt = 1, prevInflection = 0;
        if (n == 1)
            return nums;
        int[] pow = new int[n - k + 1];
        Arrays.fill(pow, -1);
        for (; rt < n; rt++) {
            if (nums[rt - 1] != nums[rt] - 1)
                prevInflection = rt;
            // System.out.println(nums[rt] + "\t" + prevInflection);
            if (rt - k + 1 >= prevInflection)
                pow[rt - k + 1] = nums[rt];
        }
        return pow;
    }
}