[LeetCode] Merge Operations to Turn Array Into a Palindrome

2422. Merge Operations to Turn Array Into a Palindrome

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int minimumOperations(vector<int>& nums) {
deque<long long> A;
for(auto n : nums) A.push_back(n);
int res = 0;
while(A.size() > 1) {
long long l = A.front(), r = A.back();
if(l == r) {
A.pop_front();
A.pop_back();
} else if(l < r) {
A.pop_front();
A.front() += l;
res += 1;
} else if(l > r) {
A.pop_back();
A.back() += r;
res += 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/10/PS/LeetCode/merge-operations-to-turn-array-into-a-palindrome/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.