#2422
Medium Algorithms Merge operations to turn array into a palindrome
Array Two Pointers Greedy
68.9% acceptance
Mar 31, 2026
153
16
You are given an array nums consisting of positive integers.
You can perform the following operation on the array any number of times:
Choose any two adjacent elements and replace them with their sum.
For example, if nums = [1,2,3,1], you can apply one operation to make it [1,5,1].
Return the minimum number of operations needed to turn the array into a palindrome.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_operations(nums: Vec<i32>) -> i32 {
let mut left = 0usize;
let mut right = nums.len() - 1;
let mut l_sum = nums[left] as i64;
let mut r_sum = nums[right] as i64;
let mut ops = 0;
while left < right {
if l_sum == r_sum {
left += 1;
right -= 1;
if left < right {
l_sum = nums[left] as i64;
r_sum = nums[right] as i64;
}
} else if l_sum < r_sum {
left += 1;
l_sum += nums[left] as i64;
ops += 1;
} else {
right -= 1;
r_sum += nums[right] as i64;
ops += 1;
}
}
ops
}
}