LeetCode in Kotlin

2659. Make Array Empty

Hard

You are given an integer array nums containing distinct numbers, and you can perform the following operations until the array is empty:

Return an integer denoting the number of operations it takes to make nums empty.

Example 1:

Input: nums = [3,4,-1]

Output: 5

Operation   Array
1           [4, -1, 3]
2           [-1, 3, 4]
3           [3, 4]
4           [4]
5           []

Example 2:

Input: nums = [1,2,4,3]

Output: 5

Operation   Array
1           [2, 4, 3]
2           [4, 3]
3           [3, 4]
4           [4]
5           []

Example 3:

Input: nums = [1,2,3]

Output: 3

Operation   Array
1           [2, 3]
2           [3]
3           []

Constraints:

Solution

class Solution {
    fun countOperationsToEmptyArray(nums: IntArray): Long {
        val sortNums = Array(nums.size) { IntArray(2) }
        for (i in nums.indices) {
            sortNums[i][0] = nums[i]
            sortNums[i][1] = i
        }
        sortNums.sortBy { it[0] }
        var res = 0L + nums.size
        for (i in 1..sortNums.lastIndex) {
            if (sortNums[i - 1][1] > sortNums[i][1]) {
                res += nums.size - i
            }
        }
        return res
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy