LeetCode in Kotlin

3984. Divisible Game

Medium

You are given an integer array nums of length n.

Alice and Bob are playing a game. Alice chooses:

Initially, both Alice’s and Bob’s scores are 0.

For each index i in the range [l, r] (inclusive):

The score difference is Alice’s score minus Bob’s score.

Alice wants to maximize the score difference. If there are multiple values of k that achieve the maximum score difference, she chooses the smallest such k.

Return the product of the maximum score difference and the chosen value of k. Since the result can be large, return it modulo 109 + 7.

Example 1:

Input: nums = [1,4,6,8]

Output: 36

Explanation:

Example 2:

Input: nums = [2,1,2]

Output: 6

Explanation:

Example 3:

Input: nums = [1]

Output: 1000000005

Explanation:

Constraints:

Solution

import kotlin.math.max
import kotlin.math.min

class Solution {
    fun divisibleGame(nums: IntArray): Int {
        val prime = HashSet<Int?>()
        val mod = 1e9.toInt() + 7
        var bestscore = nums[0].toLong()
        for (i in nums) {
            bestscore = min(bestscore, i.toLong())
        }
        bestscore = -bestscore
        var bestprime: Long = 2
        for (i in nums) {
            var i = i
            var j = 2
            while (j * j <= i) {
                if (i % j == 0) {
                    prime.add(j)
                    while (i % j == 0) {
                        i = i / j
                    }
                }
                j++
            }
            if (i > 1) {
                prime.add(i)
            }
        }
        for (p in prime) {
            var curr: Long = 0
            var maxi = Long.MIN_VALUE
            for (i in nums) {
                val `val` = (if (i % p!! == 0) i else -i).toLong()
                curr = max(0, curr + `val`)
                maxi = max(maxi, curr)
            }
            if (maxi > bestscore) {
                bestscore = maxi
                bestprime = p!!.toLong()
            } else if (maxi == bestscore && p!! < bestprime) {
                bestprime = p.toLong()
            }
        }
        bestscore = ((bestscore % mod) + mod) % mod
        return ((bestscore * (bestprime % mod)) % mod).toInt()
    }
}