3542. Minimum Operations to Convert All Elements to Zero #2403
-
|
Topics: You are given an array In one operation, you can select a subarray1 Return the minimum number of operations required to make all elements in the array 0. Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We want to find the minimum number of operations to make all elements in the array Approach:
Thus, we can use a monotonic stack to track the increasing sequence of numbers:
Let's implement this solution in PHP: 3542. Minimum Operations to Convert All Elements to Zero <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function minOperations($nums) {
$ans = 0;
$stack = [];
array_push($stack, 0);
foreach ($nums as $num) {
while (!empty($stack) && end($stack) > $num) {
array_pop($stack);
}
if (empty($stack) || end($stack) < $num) {
$ans++;
array_push($stack, $num);
}
}
return $ans;
}
// Test cases
$nums1 = [0, 2];
$nums2 = [3, 1, 2, 1];
$nums3 = [1, 2, 1, 2, 1, 2];
$nums4 = [7,2,0,4,2];
echo minOperations($nums1) . "\n"; // Output: 1
echo minOperations($nums2) . "\n"; // Output: 3
echo minOperations($nums3) . "\n"; // Output: 4
echo minOperations($nums4) . "\n"; // Output: 4
?>Explanation:
Time and Space Complexity
|
Beta Was this translation helpful? Give feedback.
We want to find the minimum number of operations to make all elements in the array
numsequal to zero.The key observation is that we only need to count the number of increasing “steps” in the array when we move from left to right.
Approach:
Thus, we can use a monotonic stack to track the increasing sequence …