[LeetCode] Largest Element in an Array after Merge Operations

2789. Largest Element in an Array after Merge Operations

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:

  • Choose an integer 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 value of the largest element that you can possibly obtain in the final array.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
long long maxArrayValue(vector<int>& nums) {
reverse(begin(nums), end(nums));
vector<long long> now{nums[0]};
for(int i = 1; i < nums.size(); i++) {
if(now.back() >= nums[i]) now.back() += nums[i];
else now.push_back(nums[i]);
}
return *max_element(begin(now), end(now));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/23/PS/LeetCode/largest-element-in-an-array-after-merge-operations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.