find index with maximum distance between two occupied seats |Amazon
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2025-02-26Added By Anonymous
Source: Link
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.
1
2import java.util.*;
3
4class MaximizeDistance {
5 public static int maxDistSeatIndex(int[] seats) {
6 int n = seats.length;
7 int maxDistance = 0;
8 int bestSeat = -1;
9 int lastOccupied = -1;
10
11 int[] rightOccupied = new int[n];
12
13 // First pass: Fill rightOccupied array with nearest occupied seat to the right
14 for (int i = n - 1; i >= 0; i--) {
15 if (seats[i] == 1) {
16 lastOccupied = i;
17 }
18 rightOccupied[i] = lastOccupied;
19 }
20
21 lastOccupied = -1;
22
23 // Second pass: Find the best seat to flip to 1
24 for (int i = 0; i < n; i++) {
25 if (seats[i] == 1) {
26 lastOccupied = i;
27 } else {
28 // Distance from the nearest left and right occupied seat
29 int leftDist = (lastOccupied == -1) ? Integer.MAX_VALUE : i - lastOccupied;
30 int rightDist = (rightOccupied[i] == -1) ? Integer.MAX_VALUE : rightOccupied[i] - i;
31
32 int minDist = Math.min(leftDist, rightDist); // Take the min of left and right distances
33
34 if (minDist > maxDistance) {
35 maxDistance = minDist;
36 bestSeat = i;
37 }
38 }
39 }
40
41 return bestSeat; // Return the index to flip
42 }
43
44 public static void main(String[] args) {
45 int[] seats = {1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0}; //6
46 int[] seats={1,0,0,0};//3
47 int[] seats={0,0,0,1};//0
48 System.out.println(maxDistSeatIndex(seats));
49 }
50}