2789. Largest Element in an Array after Merge Operations

Difficulty:
Related Topics:
Similar Questions:

Problem

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:
- Choose i = 0. The resulting array will be nums = [5,7,9,3].
- Choose i = 1. The resulting array will be nums = [5,16,3].
- Choose i = 0. The resulting array will be nums = [21,3].
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:
- Choose i = 1. The resulting array will be nums = [5,6].
- Choose i = 0. The resulting array will be nums = [11].
There is only one element in the final array, which is 11.

Constraints:

Solution (Java)

class Solution {
    public long maxArrayValue(int[] nums) {
        if(nums.length==1)
        {
            return (long)nums[0];
        }
        if(nums.length==2)
        {
            return nums[0] <= nums[1] ? (long)(nums[0]+nums[1]) : (long)(Math.max(nums[0],nums[1]));
        }
        int size=nums.length;
        long ans=0,dat=(long)nums[size-1];
        for(int i=size-2;i>=0;i--)
        {
            long val=(long)nums[i];
            if(val<=dat)
            {
                dat=dat+val;
                if(dat>ans)
                {
                    ans=dat;
                }
            }
            else
            {
                if(dat>ans)
                {
                    ans=dat;
                }
                dat=val;
            }
        }
        return dat;
    }
}

Explain:

nope.

Complexity: