2422. Merge Operations to Turn Array Into a Palindrome
Tags:
Medium
Skills:
Two pointer
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Approach
Cần kết hợp kĩ thuật two pointers và tính tổng động từ hai đầu mảng
a = nums[i] b = nums[j]ans = 01i += 1
2a += nums[i]
3ans += 11j -= 1
2b += nums[j]
3ans += 1a === b : Di chuyển cả hai pointer vào trong và cập nhật lại a, b (không tăng ans)Solution
1function minimumOperations(nums: number[]): number {
2 let i = 0;
3 let j = nums.length - 1
4 let operations = 0;
5
6 while (i < j) {
7 if (nums[i] === nums[j]) {
8 i++;
9 j--
10 } else if (nums[i] < nums[j]) {
11 nums[i + 1] += nums[i];
12 i++;
13 operations++
14 } else {
15 nums[j - 1] += nums[j]
16 j--;
17 operations++;
18 }
19 }
20 return operations
21};