Leetcode 3038. Maximum Number of Operations With the Same Score I
Given an array nums
of length n
, your goal is to find the maximum number of operations that can be performed such that every two chosen elements sum to the same score. An operation is defined as choosing two elements of the array and creating their sum.
nums
?nums
, we need to find the maximum number of pairs (i, j)
such that their sum nums[i] + nums[j]
is the same and return the count of these operations.(i, j)
in nums
and calculate their sum.#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
int maxOperationsWithSameScore(vector<int>& nums) {
// Edge case: less than two elements in the array
if (nums.size() < 2) return 0;
unordered_map<int, int> sumFrequency;
int maxOperations = 0;
for (size_t i = 0; i < nums.size(); ++i) {
for (size_t j = i + 1; j < nums.size(); ++j) {
int sum = nums[i] + nums[j];
sumFrequency[sum]++;
maxOperations = max(maxOperations, sumFrequency[sum]);
}
}
return maxOperations;
}
int main() {
vector<int> nums = {1, 2, 3, 4, 5};
cout << "Maximum number of operations: " << maxOperationsWithSameScore(nums) << endl;
return 0;
}
O(n^2)
time complexity, where n
is the number of elements in the array nums
.O(n^2)
in the worst case for the hash map storing the sums (though typically it will be much smaller).This approach ensures checking each pair efficiently, and using a hash map helps in counting frequencies seamlessly.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?