Hard
You are given a 2D array queries
, where queries[i]
is of the form [l, r]
. Each queries[i]
defines an array of integers nums
consisting of elements ranging from l
to r
, both inclusive.
In one operation, you can:
a
and b
from the array.floor(a / 4)
and floor(b / 4)
.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:
Input: queries = [[1,2],[2,4]]
Output: 3
Explanation:
For queries[0]
:
nums = [1, 2]
.nums[0]
and nums[1]
. The array becomes [0, 0]
.For queries[1]
:
nums = [2, 3, 4]
.nums[0]
and nums[2]
. The array becomes [0, 3, 1]
.nums[1]
and nums[2]
. The array becomes [0, 0, 0]
.The output is 1 + 2 = 3
.
Example 2:
Input: queries = [[2,6]]
Output: 4
Explanation:
For queries[0]
:
nums = [2, 3, 4, 5, 6]
.nums[0]
and nums[3]
. The array becomes [0, 3, 4, 1, 6]
.nums[2]
and nums[4]
. The array becomes [0, 3, 1, 1, 1]
.nums[1]
and nums[2]
. The array becomes [0, 0, 0, 1, 1]
.nums[3]
and nums[4]
. The array becomes [0, 0, 0, 0, 0]
.The output is 4.
Constraints:
1 <= queries.length <= 105
queries[i].length == 2
queries[i] == [l, r]
1 <= l < r <= 109
class Solution {
fun minOperations(queries: Array<IntArray>): Long {
var result: Long = 0
for (query in queries) {
var v: Long = 4
var req: Long = 1
var totalReq: Long = 0
while (query[0] >= v) {
v *= 4
req++
}
var group: Long
if (query[1] < v) {
group = query[1] - query[0] + 1L
totalReq += group * req
result += (totalReq + 1) / 2
continue
}
group = v - query[0]
totalReq += group * req
var bottom = v
while (true) {
v *= 4
req++
if (query[1] < v) {
group = query[1] - bottom + 1
totalReq += group * req
break
}
group = v - bottom
totalReq += group * req
bottom = v
}
result += (totalReq + 1) / 2
}
return result
}
}