Find 0 with Farthest 1s in a Binary Array
Given a string (seats) of 1s and 0s, where 1 represents a filled seat and 0 represents an empty seat in a row. Find an empty seat with maximum distance from an occupied seat. Return the maximum distance.
Examples:
Input: Seats = "1000101"
Output: 2
Explanation: Geek can take 3rd place and have a distance of 2 in left and 2 in right.Input: Seats = "1000"
Output: 3
Explanation: Geek can take the rightmost seat to have a distance of 3.
class gfg{
public int maxDis(String seats[]){
int n = seats.length();
int res = -1;
int emptySeats = 0;
for(int i = 0 ; i<n;i++){
if(seats.charAt(i) == '0'){
emptySeats++;
else if(seats.charAt(i) == '1' && res == -1){
res = emptySeats;
emptySeats = 0;
else{
res = Math.max(res,(int)Math.ceil(emptySeats/2.0));
emptySeat = 0;
}
}
res = Math.max(res,emptySeats);
return res;
}
}
Comments
Post a Comment