3355. Zero Array Transformation I #1705
-
Topics: You are given an integer array For each
A Zero Array is an array where all elements are equal to 0. Return Example 1:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine if it's possible to transform an array into a zero array by processing a series of queries. Each query allows us to select a subset of indices within a specified range and decrement their values by 1. The goal is to check if we can apply these queries in such a way that all elements in the array become zero. Approach
Let's implement this solution in PHP: 3355. Zero Array Transformation I <?php
/**
* @param Integer[] $nums
* @param Integer[][] $queries
* @return Boolean
*/
function isZeroArray($nums, $queries) {
$n = count($nums);
$diff = array_fill(0, $n + 1, 0);
foreach ($queries as $q) {
$l = $q[0];
$r = $q[1];
$diff[$l]++;
if ($r + 1 < $n) {
$diff[$r + 1]--;
}
}
$current = 0;
$Q = array();
for ($i = 0; $i < $n; $i++) {
$current += $diff[$i];
$Q[$i] = $current;
}
foreach ($nums as $i => $val) {
if ($Q[$i] < $val) {
return false;
}
}
$sum_ranges = 0;
foreach ($queries as $q) {
$l = $q[0];
$r = $q[1];
$sum_ranges += ($r - $l + 1);
}
$sum_nums = array_sum($nums);
if ($sum_nums > $sum_ranges) {
return false;
}
return true;
}
// Example usage:
$nums1 = [1, 0, 1];
$queries1 = [[0, 2]];
var_dump(isZeroArray($nums1, $queries1)); // true
$nums2 = [4, 3, 2, 1];
$queries2 = [[1, 3], [0, 2]];
var_dump(isZeroArray($nums2, $queries2)); // false
?> Explanation:
By combining these checks, we efficiently determine if transforming the array into a zero array is feasible. |
Beta Was this translation helpful? Give feedback.
We need to determine if it's possible to transform an array into a zero array by processing a series of queries. Each query allows us to select a subset of indices within a specified range and decrement their values by 1. The goal is to check if we can apply these queries in such a way that all elements in the array become zero.
Approach