LeetCode 2984: Find Peak Calling Hours for Each City Solution
Master LeetCode problem 2984 (Find Peak Calling Hours for Each City), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2984. Find Peak Calling Hours for Each City
Problem Explanation
Explanation:
This problem can be solved using a sliding window approach. We will iterate through the input array and maintain a sliding window of size k to calculate the peak calling hours for each city. The peak calling hours for a city are the maximum total call minutes within any consecutive k hours.
Algorithm:
- Initialize a hashmap to store the total call minutes for each city.
- Initialize two pointers
leftandrightto define the sliding window. - Iterate through the input array using the
rightpointer. - Add the call minutes of the current city to the hashmap.
- If the window size is greater than
k, remove the call minutes of the city at theleftpointer from the hashmap and incrementleft. - After processing each window, update the maximum total call minutes for each city.
- Return the peak calling hours for each city.
Time Complexity: O(n) Space Complexity: O(n)
:
Solution Code
import java.util.*;
class Solution {
public int[] findPeakCallingHours(int[] calls, int k) {
Map<Integer, Integer> cityCalls = new HashMap<>();
int left = 0;
int maxMinutes = 0;
int[] peakCallingHours = new int[calls.length - k + 1];
for (int right = 0; right < calls.length; right++) {
cityCalls.put(calls[right], cityCalls.getOrDefault(calls[right], 0) + 1);
if (right - left + 1 > k) {
cityCalls.put(calls[left], cityCalls.get(calls[left]) - 1);
if (cityCalls.get(calls[left]) == 0) {
cityCalls.remove(calls[left]);
}
left++;
}
if (right - left + 1 == k) {
int totalMinutes = cityCalls.keySet().stream().mapToInt(city -> city * cityCalls.get(city)).sum();
maxMinutes = Math.max(maxMinutes, totalMinutes);
peakCallingHours[left] = maxMinutes;
}
}
return peakCallingHours;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2984 (Find Peak Calling Hours for Each City)?
This page provides optimized solutions for LeetCode problem 2984 (Find Peak Calling Hours for Each City) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2984 (Find Peak Calling Hours for Each City)?
The time complexity for LeetCode 2984 (Find Peak Calling Hours for Each City) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2984 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2984 in Java, C++, or Python.