Leetcode 3184. Count Pairs That Form a Complete Day I
You are given a list of integers days
, where each integer represents a number of hours worked on a day. A complete day is defined to be 24 hours or more.
You need to count how many pairs (i, j)
exist, where i < j
and the sum of days[i] + days[j]
is greater than or equal to 24.
days
always have at least two elements?days
list, such as non-negative integers?days[i] + days[j]
equals exactly 24?Assuming typical constraints and conditions unless clarified otherwise.
(i, j)
where i < j
.days[i] + days[j] >= 24
.days
.left
) and one at the end (right
) of the sorted list.We will implement both approaches in C++.
#include <vector>
int countPairsBruteForce(const std::vector<int>& days) {
int count = 0;
for (size_t i = 0; i < days.size(); ++i) {
for (size_t j = i + 1; j < days.size(); ++j) {
if (days[i] + days[j] >= 24) {
++count;
}
}
}
return count;
}
#include <vector>
#include <algorithm>
int countPairsOptimized(std::vector<int>& days) {
std::sort(days.begin(), days.end());
int count = 0;
int left = 0;
int right = days.size() - 1;
while (left < right) {
if (days[left] + days[right] >= 24) {
// All pairs (left, right), (left, right-1), ... (left, left+1) are valid
count += (right - left);
--right;
} else {
++left;
}
}
return count;
}
n
is the number of elements in days
.With these implementations, you can choose based on the size of the input for efficiency. The optimized approach is more efficient for larger datasets.
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?