Input: nums =[3,2,1,4,5]Output: 2Explanation:
* We can perform the first operation with the score `3 + 2 = 5`. After this operation,`nums = [1,4,5]`.* We can perform the second operation as its score is`4 + 1 = 5`, the same as the previous operation. After this operation,`nums = [5]`.* As there are fewer than two elements, we can't perform more operations.
Input: nums =[1,5,3,3,4,1,3,2,2,3]Output: 2Explanation:
* We can perform the first operation with the score `1 + 5 = 6`. After this operation,`nums = [3,3,4,1,3,2,2,3]`.* We can perform the second operation as its score is`3 + 3 = 6`, the same as the previous operation. After this operation,`nums = [4,1,3,2,2,3]`.* We cannot perform the next operation as its score is`4 + 1 = 5`, which is different from the previous scores.
The score for each operation is the sum of the first two elements. To maximize the number of operations, try all possible initial scores (from the first two elements), and simulate the process for each, counting how many times you can keep removing pairs with the same score.
classSolution {
public:int maxOperations(vector<int>& nums) {
int n = nums.size(), ans =0;
for (int i =1; i < n; ++i) {
int score = nums[0] + nums[i];
int cnt =0, l =0, r = i;
while (r +1< n) {
if (nums[l] + nums[r] == score) {
cnt++;
l = r +1;
r = l +1;
} else {
break;
}
}
ans = max(ans, cnt +1);
}
return ans;
}
};
classSolution {
publicintmaxOperations(int[] nums) {
int n = nums.length, ans = 0;
for (int i = 1; i < n; i++) {
int score = nums[0]+ nums[i];
int cnt = 0, l = 0, r = i;
while (r + 1 < n) {
if (nums[l]+ nums[r]== score) {
cnt++;
l = r + 1;
r = l + 1;
} else {
break;
}
}
ans = Math.max(ans, cnt + 1);
}
return ans;
}
}
classSolution {
funmaxOperations(nums: IntArray): Int {
val n = nums.size
var ans = 0for (i in1 until n) {
val score = nums[0] + nums[i]
var cnt = 0var l = 0var r = i
while (r + 1 < n) {
if (nums[l] + nums[r] == score) {
cnt++ l = r + 1 r = l + 1 } else {
break }
}
ans = maxOf(ans, cnt + 1)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defmaxOperations(self, nums: list[int]) -> int:
n = len(nums)
ans =0for i in range(1, n):
score = nums[0] + nums[i]
cnt, l, r =0, 0, i
while r +1< n:
if nums[l] + nums[r] == score:
cnt +=1 l = r +1 r = l +1else:
break ans = max(ans, cnt +1)
return ans
impl Solution {
pubfnmax_operations(nums: Vec<i32>) -> i32 {
let n = nums.len();
letmut ans =0;
for i in1..n {
let score = nums[0] + nums[i];
letmut cnt =0;
letmut l =0;
letmut r = i;
while r +1< n {
if nums[l] + nums[r] == score {
cnt +=1;
l = r +1;
r = l +1;
} else {
break;
}
}
ans = ans.max(cnt +1);
}
ans
}
}