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 thelargest element that you can possibly obtain in the final array.
Input: nums =[2,3,7,9,3]Output: 21Explanation: 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 is21. It can be shown that we cannot obtain a larger element.
Input: nums =[5,3,3]Output: 11Explanation: 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 is11.
To maximize the largest element, we should merge as many elements as possible into a single value, but only when the left element is less than or equal to the right. By traversing from the end, we can greedily merge leftwards whenever possible, always keeping the largest possible sum.
classSolution {
public:longlong maxArrayValue(vector<int>& nums) {
longlong ans =0, sum =0;
for (int i = nums.size() -1; i >=0; --i) {
if (nums[i] <= sum) sum += nums[i];
else sum = nums[i];
ans = max(ans, sum);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcmaxArrayValue(nums []int) int64 {
ans, sum:= int64(0), int64(0)
fori:= len(nums)-1; i>=0; i-- {
if int64(nums[i]) <=sum {
sum+= int64(nums[i])
} else {
sum = int64(nums[i])
}
ifsum > ans { ans = sum }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publiclongmaxArrayValue(int[] nums) {
long ans = 0, sum = 0;
for (int i = nums.length- 1; i >= 0; --i) {
if (nums[i]<= sum) sum += nums[i];
else sum = nums[i];
ans = Math.max(ans, sum);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funmaxArrayValue(nums: IntArray): Long {
var ans = 0Lvar sum = 0Lfor (i in nums.indices.reversed()) {
sum = if (nums[i] <= sum) sum + nums[i] else nums[i].toLong()
ans = maxOf(ans, sum)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defmaxArrayValue(self, nums: list[int]) -> int:
ans =0 s =0for x in reversed(nums):
if x <= s:
s += x
else:
s = x
ans = max(ans, s)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnmax_array_value(nums: Vec<i32>) -> i64 {
letmut ans =0i64;
letmut sum =0i64;
for&x in nums.iter().rev() {
if x asi64<= sum {
sum += x asi64;
} else {
sum = x asi64;
}
if sum > ans { ans = sum; }
}
ans
}
}