Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

#include #include #include #include #include int findConsistentLogs ( const std::vector& userEvent ) { int n = userEvent.size ( ) ; / / Step 1 :

#include
#include
#include
#include
#include
int findConsistentLogs(const std::vector& userEvent){
int n = userEvent.size();
// Step 1: Calculate the minimum frequency in the entire array
std::unordered_map freq;
for (int user : userEvent){
freq[user]+=1;
}
int min_freq = INT_MAX;
for (const auto& entry : freq){
min_freq = std::min(min_freq, entry.second);
}
// Step 2: Use sliding window to find the longest consistent subarray
int max_length =0;
std::unordered_map window_freq;
int left =0;
for (int right =0; right < n; ++right){
window_freq[userEvent[right]]+=1;
// Check if the current window is consistent
while (*std::max_element(window_freq.begin(), window_freq.end(),
[](const std::pair& a, const std::pair& b){ return a.second < b.second; })->second > min_freq){
window_freq[userEvent[left]]-=1;
if (window_freq[userEvent[left]]==0){
window_freq.erase(userEvent[left]);
}
left +=1;
}
// Update the maximum length of consistent subarray
max_length = std::max(max_length, right - left +1);
}
return max_length;
}
int main(){
std::vector userEvent ={1,2,1,3,4,2,4,3,3,3};
std::cout << findConsistentLogs(userEvent)<< std::endl; // Output: 8
return 0;
}
Please optimize this code

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions