Input: nums =[4,3,2,1,2,3,1]Output: 2Explanation: We can turn the array into a palindrome in2 operations as follows:- Apply the operation on the fourth and fifth element of the array, nums becomes equal to [4,3,2,**_3_**,3,1].- Apply the operation on the fifth and sixth element of the array, nums becomes equal to [4,3,2,3,**_4_**].The array [4,3,2,3,4]is a palindrome.It can be shown that 2is the minimum number of operations needed.
Example 2:
1
2
3
Input: nums =[1,2,3,4]Output: 3Explanation: We do the operation 3 times in any position, we obtain the array [10] at the end which is a palindrome.
To make the array a palindrome with minimum operations, use two pointers from both ends. If the values are equal, move both pointers inward. If not, merge the smaller value with its neighbor, incrementing the operation count, and continue until the array is a palindrome.
classSolution {
publicintminimumOperations(int[] nums) {
int l = 0, r = nums.length- 1, ans = 0;
while (l < r) {
if (nums[l]== nums[r]) {
l++; r--;
} elseif (nums[l]< nums[r]) {
nums[l + 1]+= nums[l];
l++; ans++;
} else {
nums[r - 1]+= nums[r];
r--; ans++;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funminimumOperations(nums: IntArray): Int {
var l = 0; var r = nums.size - 1; var ans = 0while (l < r) {
if (nums[l] == nums[r]) {
l++; r-- } elseif (nums[l] < nums[r]) {
nums[l + 1] += nums[l]
l++; ans++ } else {
nums[r - 1] += nums[r]
r--; ans++ }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
defminimum_operations(nums: list[int]) -> int:
l, r =0, len(nums) -1 ans =0while l < r:
if nums[l] == nums[r]:
l +=1; r -=1elif nums[l] < nums[r]:
nums[l +1] += nums[l]
l +=1; ans +=1else:
nums[r -1] += nums[r]
r -=1; ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnminimum_operations(nums: &mut Vec<i32>) -> i32 {
let (mut l, mut r, mut ans) = (0, nums.len() -1, 0);
while l < r {
if nums[l] == nums[r] {
l +=1; r -=1;
} elseif nums[l] < nums[r] {
nums[l +1] += nums[l];
l +=1; ans +=1;
} else {
nums[r -1] += nums[r];
r -=1; ans +=1;
}
}
ans
}
}