3495. Minimum Operations to Make Array Elements Zero #2140
-
3495. Minimum Operations to Make Array Elements Zero Difficulty: Hard Topics: You are given a 2D array In one operation, you can:
Your task is to determine the minimum number of operations required to reduce all elements of the array to zero for each query. Return the sum of the results for all queries. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to compute the minimum number of operations to reduce all numbers to zero. Here’s the plan: Approach:
Let's implement this solution in PHP: 3495. Minimum Operations to Make Array Elements Zero <?php
/**
* @param Integer[][] $queries
* @return Integer
*/
function minOperations($queries) {
$bounds = [];
$low = 1;
for ($k = 1; $k <= 16; $k++) {
$high = $low * 4 - 1;
$bounds[] = ['low' => $low, 'high' => $high, 'k' => $k];
$low = $high + 1;
}
$total_ans = 0;
foreach ($queries as $q) {
$l = $q[0];
$r = $q[1];
$S = 0;
$M = 0;
foreach ($bounds as $b) {
$low_b = $b['low'];
$high_b = $b['high'];
$k_val = $b['k'];
if ($low_b > $r) {
break;
}
if ($high_b < $l) {
continue;
}
$A = max($l, $low_b);
$B = min($r, $high_b);
if ($A <= $B) {
$count = $B - $A + 1;
$S += $count * $k_val;
if ($k_val > $M) {
$M = $k_val;
}
}
}
$ops = max( (int)ceil($S / 2), $M );
$total_ans += $ops;
}
return $total_ans;
}
// Test cases
$queries1 = [[1,2],[2,4]];
echo minOperations($queries1) . PHP_EOL; // 3
$queries2 = [[2,6]];
echo minOperations($queries2) . PHP_EOL; // 4
?> Explanation:
This approach efficiently processes each query by leveraging precomputed ranges and ensures optimal performance even for large inputs. The complexity is linear with respect to the number of queries, making it suitable for the given constraints. |
Beta Was this translation helpful? Give feedback.
We need to compute the minimum number of operations to reduce all numbers to zero. Here’s the plan:
Approach:
k
(the number of operations needed to reduce a number to zero), determine the range of numbers that require exactlyk
operations. This is done by noting that numbers in the range[4(k-1), 4k - 1]
requirek
operations.[l, r]
, calculate the total number of operationsT
needed by summing the contributions of all numbers in the range[l, r]
. Each number in a precomputed range[low, high]
contributesk
toT
. Also, track the maximumk
valueM
encountered in the range.