3495. Minimum Operations to Make Array Elements Zero
EasyView on LeetCode
Time: O(q * log max)
Space: O(1)
Problem Overview
Minimum Operations to Make Array Elements Zero (Easy) asks you to solve a structured algorithmic task. This is a common Array / Math pattern in coding interviews. For each query range pair count non-zero groups; sum ceil(log4(max)) per group.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
For each query range pair count non-zero groups; sum ceil(log4(max)) per group.
Related patterns: Array, Math, Bit Manipulation
3495.cs
C#
// Approach: For each query range pair count non-zero groups; sum ceil(log4(max)) per group.
// Time: O(q * log max) Space: O(1)
public class Solution
{
public long MinOperations(int[][] queries)
{
long ans = 0;
foreach (var query in queries)
{
int l = query[0];
int r = query[1];
ans += (GetOperations(r) - GetOperations(l - 1) + 1) / 2;
}
return ans;
}
// Returns the number of operations required for [1, n].
private long GetOperations(int n)
{
long res = 0;
int ops = 0;
for (int powerOfFour = 1; powerOfFour <= n; powerOfFour *= 4)
{
int l = powerOfFour;
int r = Math.Min(n, powerOfFour * 4 - 1);
res += (long)(r - l + 1) * ++ops;
}
return res;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)