Leetcode 2078. Two Furthest Houses With Different Colors
This problem requires finding the maximum distance between two houses in a row that have different colors. The input is an array colors
where each element represents the color of the house at that position.
Example:
colors = [1,1,1,6,1,1,1]
3
Explanation:
To be thorough, let’s confirm a few details:
For the purposes of this solution, we will assume:
#include <vector>
#include <algorithm>
class Solution {
public:
int maxDistance(std::vector<int>& colors) {
int n = colors.size();
int maxDist = 0;
// Check from start to end
for (int i = 0; i < n; ++i) {
if (colors[i] != colors[0]) {
maxDist = std::max(maxDist, i);
}
}
// Check from end to start
for (int i = n - 1; i >= 0; --i) {
if (colors[i] != colors[n - 1]) {
maxDist = std::max(maxDist, n - 1 - i);
}
}
return maxDist;
}
};
// Example usage
// int main() {
// Solution sol;
// std::vector<int> colors = {1,1,1,6,1,1,1};
// std::cout << "Maximum distance: " << sol.maxDistance(colors) << std::endl;
// return 0;
// }
The time complexity of this solution is O(n), where n
is the number of houses. This is because we are essentially traversing the list of houses twice, once from the beginning and once from the end. This is more optimal than the O(n^2) brute force approach.
maxDist
to zero.maxDist
is the maximum of these two distances, which gives our final answer.This approach ensures that we efficiently find the maximum distance between the furthest houses with different colors.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?