find index with maximum distance between two occupied seats |Amazon
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2025-02-26Added By Anonymous
Source: Link
Company: Amazon
Role: unknown
Interview Stage: unknown
Location: unknown
Year: unknown
Original Post Content:
You are given an array seats where:
1 represents an occupied seat.
0 represents an empty seat.
Your task is to determine the index of the empty seat (0) that should be flipped to 1 such that the minimum distance to the nearest occupied seat (1) is maximized.
\nimport java.util.*;\n\nclass MaximizeDistance {\n public static int maxDistSeatIndex(int[] seats) {\n int n = seats.length;\n int maxDistance = 0;\n int bestSeat = -1;\n int lastOccupied = -1;\n\n int[] rightOccupied = new int[n];\n\n // First pass: Fill rightOccupied array with nearest occupied seat to the right\n for (int i = n - 1; i >= 0; i--) {\n if (seats[i] == 1) {\n lastOccupied = i;\n }\n rightOccupied[i] = lastOccupied;\n }\n\n lastOccupied = -1;\n\n // Second pass: Find the best seat to flip to 1\n for (int i = 0; i < n; i++) {\n if (seats[i] == 1) {\n lastOccupied = i;\n } else {\n // Distance from the nearest left and right occupied seat\n int leftDist = (lastOccupied == -1) ? Integer.MAX_VALUE : i - lastOccupied;\n int rightDist = (rightOccupied[i] == -1) ? Integer.MAX_VALUE : rightOccupied[i] - i;\n\n int minDist = Math.min(leftDist, rightDist); // Take the min of left and right distances\n\n if (minDist > maxDistance) {\n maxDistance = minDist;\n bestSeat = i;\n }\n }\n }\n\n return bestSeat; // Return the index to flip\n }\n\n public static void main(String[] args) {\n int[] seats = {1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0}; //6\n\t\tint[] seats={1,0,0,0};//3\n\t\tint[] seats={0,0,0,1};//0\n System.out.println(maxDistSeatIndex(seats)); \n }\n}\n