LeetCode 2078: Two Furthest Houses With Different Colors Solution
Master LeetCode problem 2078 (Two Furthest Houses With Different Colors), 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.
Problem Explanation
Explanation:
To solve this problem, we can iterate through the array once while keeping track of the positions where each color occurs for the first time and the maximum distance between two different colors. We can achieve this by storing the position of each color in a map and updating the maximum distance when we encounter a color that we have seen before.
- Initialize a map to store the position of each color seen so far.
- Initialize a variable
maxDistanceto 0 to keep track of the maximum distance between two different colors. - Iterate through the array:
- If the current color is not in the map, add it with its position.
- If the current color is already in the map, update
maxDistanceif the distance between the current position and the position of the color in the map is greater than the currentmaxDistance.
- Return the
maxDistance.
:
Solution Code
class Solution {
public int maxDistance(int[] colors) {
Map<Integer, Integer> colorPositions = new HashMap<>();
int maxDistance = 0;
for (int i = 0; i < colors.length; i++) {
if (colorPositions.containsKey(colors[i])) {
maxDistance = Math.max(maxDistance, i - colorPositions.get(colors[i]));
} else {
colorPositions.put(colors[i], i);
}
}
return maxDistance;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2078 (Two Furthest Houses With Different Colors)?
This page provides optimized solutions for LeetCode problem 2078 (Two Furthest Houses With Different Colors) 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 2078 (Two Furthest Houses With Different Colors)?
The time complexity for LeetCode 2078 (Two Furthest Houses With Different Colors) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2078 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2078 in Java, C++, or Python.