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
isuch that0 <= i < nums.length - 1andnums[i] <= nums[i + 1] - Replace the element
nums[i + 1]withnums[i] + nums[i + 1]and delete the elementnums[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
Understanding the Visualization
1
Input Array
Array [2,1,3,4] with merge rule: left ≤ right
2
Valid Merges
Find positions where nums[i] ≤ nums[i+1]
3
Optimal Result
Maximum possible value after all beneficial merges
Key Takeaway
🎯 Key Insight: Process from right to left - each element can absorb all smaller elements to its left
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code