LeetCode in Kotlin

2789. Largest Element in an Array after Merge Operations

Medium

You are given a 0-indexed array nums consisting of positive integers.

You can do the following operation on the array any number of times:

Return the value of the largest element that you can possibly obtain in the final array.

Example 1:

Input: nums = [2,3,7,9,3]

Output: 21

Explanation:

We can apply the following operations on the array:

The largest element in the final array is 21. It can be shown that we cannot obtain a larger element.

Example 2:

Input: nums = [5,3,3]

Output: 11

Explanation:

We can do the following operations on the array:

There is only one element in the final array, which is 11.

Constraints:

Solution

class Solution {
    fun maxArrayValue(nums: IntArray): Long {
        var ans = nums[nums.size - 1].toLong()
        for (i in nums.size - 1 downTo 1) {
            if (ans >= nums[i - 1]) {
                ans += nums[i - 1].toLong()
            } else {
                ans = nums[i - 1].toLong()
            }
        }
        return ans
    }
}