LeetCode in Kotlin

3038. Maximum Number of Operations With the Same Score I

Easy

Given an array of integers called nums, you can perform the following operation while nums contains at least 2 elements:

The score of the operation is the sum of the deleted elements.

Your task is to find the maximum number of operations that can be performed, such that all operations have the same score.

Return the maximum number of operations possible that satisfy the condition mentioned above.

Example 1:

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

Output: 2

Explanation: We perform the following operations:

We are unable to perform any more operations as nums contain only 1 element.

Example 2:

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

Output: 1

Explanation: We perform the following operations:

We are unable to perform any more operations as the score of the next operation isn’t the same as the previous one.

Constraints:

Solution

class Solution {
    fun maxOperations(nums: IntArray): Int {
        var c = 1
        var i = 2
        val s = nums[0] + nums[1]
        val l = nums.size - (if (nums.size % 2 == 0) 0 else 1)
        while (i < l) {
            if (nums[i] + nums[i + 1] == s) {
                c++
            } else {
                break
            }
            i += 2
        }
        return c
    }
}