LeetCode in Kotlin

3994. Minimum Adjacent Swaps to Partition Array

Medium

You are given an integer array nums and two integers a and b such that a < b.

An array is called good if it can be split into three contiguous parts, in this order, such that:

Any of the three parts may be empty.

In one adjacent swap, you may swap two neighboring elements of nums.

Return the minimum number of adjacent swaps required to make nums good. Since the answer may be very large, return it modulo 109 + 7.

Example 1:

Input: nums = [1,3,2,4,5,6], a = 3, b = 4

Output: 1

Explanation:

Example 2:

Input: nums = [9,7,5,3], a = 4, b = 8

Output: 5

Explanation:

One sequence of optimal swaps is as follows:

Example 3:

Input: nums = [3,7,5,9], a = 4, b = 8

Output: 0

Explanation:

The array is already good. No swaps are needed.

Constraints:

Solution

class Solution {
    fun minAdjacentSwaps(nums: IntArray, a: Int, b: Int): Int {
        var ans: Long = 0
        var c1: Long = 0
        var c2: Long = 0
        for (v in nums) {
            if (v < a) {
                ans += c1 + c2
            } else if (v <= b) {
                c1++
                ans += c2
            } else {
                c2++
            }
        }
        return (ans % 1000000007).toInt()
    }
}