LeetCode 2987: Find Expensive Cities Solution
Master LeetCode problem 2987 (Find Expensive Cities), a easy 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.
2987. Find Expensive Cities
Problem Explanation
Explanation:
To find expensive cities, we can iterate through the given list of cities and their prices, keeping track of the highest price seen so far. We will also maintain a set to store the names of the expensive cities. If we encounter a price higher than the current highest price, we update the highest price and update the set of expensive cities.
- Initialize a variable
maxPriceto store the highest price seen so far. - Initialize an empty set
expensiveCitiesto store the names of expensive cities. - Iterate through the list of cities and their prices.
- If the price is higher than
maxPrice, updatemaxPriceand clearexpensiveCities. - Add the current city to
expensiveCities. - Return the set
expensiveCities.
Solution Code
import java.util.*;
class Solution {
public Set<String> findExpensiveCities(List<String> cities, List<Integer> prices) {
int maxPrice = Integer.MIN_VALUE;
Set<String> expensiveCities = new HashSet<>();
for (int i = 0; i < prices.size(); i++) {
if (prices.get(i) > maxPrice) {
maxPrice = prices.get(i);
expensiveCities.clear();
expensiveCities.add(cities.get(i));
} else if (prices.get(i) == maxPrice) {
expensiveCities.add(cities.get(i));
}
}
return expensiveCities;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2987 (Find Expensive Cities)?
This page provides optimized solutions for LeetCode problem 2987 (Find Expensive Cities) 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 2987 (Find Expensive Cities)?
The time complexity for LeetCode 2987 (Find Expensive Cities) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2987 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2987 in Java, C++, or Python.