Largest Element in an Array after Merge Operations - Problem

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

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

  • Choose an index i such that 0 <= i < nums.length - 1 and nums[i] <= nums[i + 1]
  • Replace the element nums[i + 1] with nums[i] + nums[i + 1] and delete the element nums[i] from the array

Return the largest element that you can possibly obtain in the final array after performing the merge operations optimally.

Input & Output

Example 1 — Basic Merging
$ Input: nums = [2,1,3,4]
Output: 10
💡 Note: Working right-to-left: Start with 4. Since 3 ≤ 4, merge to get 7. Since 1 ≤ 7, merge to get 8. Since 2 ≤ 8, merge to get 10. Final answer is 10.
Example 2 — Cannot Merge All
$ Input: nums = [5,3,3]
Output: 6
💡 Note: Start with 3. Since 3 ≤ 3, merge to get 6. Since 5 > 6, cannot merge. Maximum between 5 and 6 is 6.
Example 3 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: Only one element, so the maximum possible value is 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Largest Element After Merge Operations INPUT nums = [2, 1, 3, 4] 2 i=0 1 i=1 3 i=2 4 i=3 Merge Rule: If nums[i] <= nums[i+1] Merge: nums[i+1] += nums[i] Goal: Find maximum possible element ALGORITHM STEPS (Greedy Right-to-Left) 1 Start from right sum = 4 (last element) 2 Check i=2: nums[2]=3 3 <= 4? Yes! sum = 3+4 = 7 3 Check i=1: nums[1]=1 1 <= 7? Yes! sum = 1+7 = 8 4 Check i=0: nums[0]=2 2 <= 8? Yes! sum = 2+8 = 10 Merge Process: [2,1,3,4] --> sum=4 [2,1,7] --> sum=7 [2,8] --> sum=8 [10] --> sum=10 FINAL RESULT Largest Element: 10 Final Array: [10] OK - All merged! 2+1+3+4 = 10 Maximum achieved Output: 10 Key Insight: By traversing right-to-left, we greedily accumulate elements into a running sum whenever possible. If nums[i] <= current_sum, we can always merge. Track the maximum sum seen as the answer. Time: O(n) | Space: O(1) - Single pass greedy approach TutorialsPoint - Largest Element in an Array after Merge Operations | Greedy Right-to-Left Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
23.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen