LeetCode in Kotlin

3207. Maximum Points After Enemy Battles

Medium

You are given an integer array enemyEnergies denoting the energy values of various enemies.

You are also given an integer currentEnergy denoting the amount of energy you have initially.

You start with 0 points, and all the enemies are unmarked initially.

You can perform either of the following operations zero or multiple times to gain points:

Return an integer denoting the maximum points you can get in the end by optimally performing operations.

Example 1:

Input: enemyEnergies = [3,2,2], currentEnergy = 2

Output: 3

Explanation:

The following operations can be performed to get 3 points, which is the maximum:

Example 2:

Input: enemyEnergies = [2], currentEnergy = 10

Output: 5

Explanation:

Performing the first operation 5 times on enemy 0 results in the maximum number of points.

Constraints:

Solution

import kotlin.math.min

class Solution {
    fun maximumPoints(enemyEnergies: IntArray, currentEnergy: Int): Long {
        val n = enemyEnergies.size
        var min = enemyEnergies[0]
        for (i in 1 until n) {
            min = min(min.toDouble(), enemyEnergies[i].toDouble()).toInt()
        }
        if (currentEnergy == 0 || currentEnergy < min) {
            return 0
        }
        var sum = currentEnergy.toLong()
        for (i in n - 1 downTo 0) {
            sum += enemyEnergies[i].toLong()
        }
        sum -= min.toLong()
        return sum / min
    }
}