Skip to content

Instantly share code, notes, and snippets.

@guid-empty
Created September 6, 2023 20:02
Show Gist options
  • Save guid-empty/f94495cfc06d4bcfb3d2c340c8d11606 to your computer and use it in GitHub Desktop.
Save guid-empty/f94495cfc06d4bcfb3d2c340c8d11606 to your computer and use it in GitHub Desktop.
Leetcode -> Maximize Distance to Closest Person
import 'dart:math';
///
/// https://leetcode.com/problems/maximize-distance-to-closest-person/description/
/// 849. Maximize Distance to Closest Person
///
/// You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
/// There is at least one empty seat, and at least one person sitting.
/// Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
/// Return that maximum distance to the closest person.
///
/// Лучшее решение
/// https://leetcode.com/problems/maximize-distance-to-closest-person/solutions/1694683/best-explanation-ever-possible-for-this-question/
///
///
void main() {
print('results is ${maxDistToClosest([1, 0, 0, 0, 1, 0, 1])}');
print('results is ${maxDistToClosest([1, 0, 1])}');
print('results is ${maxDistToClosest([0, 0, 0, 1, 0, 0])}');
print('results is ${maxDistToClosest([1, 0, 0, 1, 0, 0])}');
}
int maxDistToClosest(List<int> seats) {
int n = seats.length;
int empty = 0;
int result = 0;
int idx1 = -1, idx2 = -1;
// индексы слева и справа к единице
// для последовательности нулей слева это должна быть первая единица
// для последовательности нулей справа это будет просто последняя единица
// и мы считаем, что ДО idx1 и после idx2 могут быть НУЛИ
for (int i = 0; i < n; ++i) {
print(seats[i]);
if (seats[i] == 1) {
empty = 0;
if (idx1 == -1) idx1 = i;
idx2 = i;
print((111, idx1, idx2));
} else {
empty++;
result = max(result, ((empty + 1) / 2).round());
print((222, empty, result));
}
}
result = max(result, max(idx1, n - 1 - idx2));
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment