LeetCode in Kotlin

3495. Minimum Operations to Make Array Elements Zero

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:

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]:

For queries[1]:

The output is 1 + 2 = 3.

Example 2:

Input: queries = [[2,6]]

Output: 4

Explanation:

For queries[0]:

The output is 4.

Constraints:

Solution

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
    }
}