Skip to content

Latest commit

 

History

History

2772

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

You are given a 0-indexed integer array nums and a positive integer k.

You can apply the following operation on the array any number of times:

  • Choose any subarray of size k from the array and decrease all its elements by 1.

Return true if you can make all the array elements equal to 0, or false otherwise.

A subarray is a contiguous non-empty part of an array.

 

Example 1:

Input: nums = [2,2,3,1,1,0], k = 3
Output: true
Explanation: We can do the following operations:
- Choose the subarray [2,2,3]. The resulting array will be nums = [1,1,2,1,1,0].
- Choose the subarray [2,1,1]. The resulting array will be nums = [1,1,1,0,0,0].
- Choose the subarray [1,1,1]. The resulting array will be nums = [0,0,0,0,0,0].

Example 2:

Input: nums = [1,3,1,1], k = 2
Output: false
Explanation: It is not possible to make all the array elements equal to 0.

 

Constraints:

  • 1 <= k <= nums.length <= 105
  • 0 <= nums[i] <= 106

Companies: Hudson River Trading

Related Topics:
Array, Prefix Sum

Similar Questions:

Solution 1. Diff Array

// OJ: https://leetcode.com/problems/apply-operations-to-make-all-array-elements-equal-to-zero
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    bool checkArray(vector<int>& A, int k) {
        int N = A.size(), d = 0; 
        vector<int> diff(N + 1); 
class Solution {
public:
    bool checkArray(vector<int>& A, int k) {
        int N = A.size(), d = 0; // `d` is what we need to subtract at A[i]
        vector<int> diff(N + 1); // when we need to additionally subtract `x` at A[i], we set `diff[i + k] = -x.
        for (int i = 0; i < N; ++i) {
            d += diff[i];
            A[i] -= d;
            if (A[i] < 0) return false; // If A[i] becomes negative after subtracting d, return false
            if (A[i] > 0) { // If there is still some remnant A[i], we add it to `d` and set `diff[i + k] = -A[i]`.
                d += A[i];
                if (i + k > N) return false;  
                diff[i + k] = -A[i];
            } 
        }
        return true;
    }
};