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.

  1. Initialize a variable maxPrice to store the highest price seen so far.
  2. Initialize an empty set expensiveCities to store the names of expensive cities.
  3. Iterate through the list of cities and their prices.
  4. If the price is higher than maxPrice, update maxPrice and clear expensiveCities.
  5. Add the current city to expensiveCities.
  6. 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.

Back to LeetCode Solutions