LeetCode 2285: Maximum Total Importance of Roads Solution

Master LeetCode problem 2285 (Maximum Total Importance of Roads), 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.

2285. Maximum Total Importance of Roads

Problem Explanation

Explanation:

To solve this problem, we can use a greedy algorithm approach. We want to assign values to cities in such a way that the total importance of all roads is maximized. We can achieve this by assigning the highest values to cities that are most frequently connected by roads.

  1. Create a map to store the frequency of each city appearing in the roads array.
  2. Sort the cities based on their frequency in descending order.
  3. Assign values starting from the highest value to the most frequent city, then decrement the value for subsequent cities.
  4. Calculate the total importance of roads by summing the importance of each road.

Time Complexity:
The time complexity of this approach is O(n log n) where n is the number of cities.

Space Complexity:
The space complexity is O(n) to store the frequency map.

:

Solution Code

class Solution {
    public int maxTotalImportance(int n, int[][] roads) {
        Map<Integer, Integer> freqMap = new HashMap<>();
        for (int[] road : roads) {
            freqMap.put(road[0], freqMap.getOrDefault(road[0], 0) + 1);
            freqMap.put(road[1], freqMap.getOrDefault(road[1], 0) + 1);
        }

        List<Integer> cities = new ArrayList<>(freqMap.keySet());
        cities.sort((a, b) -> freqMap.get(b) - freqMap.get(a));

        int[] values = new int[n];
        int value = n;
        for (int city : cities) {
            values[city] = value;
            value--;
        }

        int totalImportance = 0;
        for (int[] road : roads) {
            totalImportance += values[road[0]] + values[road[1]];
        }

        return totalImportance;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2285 (Maximum Total Importance of Roads)?

This page provides optimized solutions for LeetCode problem 2285 (Maximum Total Importance of Roads) 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 2285 (Maximum Total Importance of Roads)?

The time complexity for LeetCode 2285 (Maximum Total Importance of Roads) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2285 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2285 in Java, C++, or Python.

Back to LeetCode Solutions