aboutsummaryrefslogtreecommitdiff
path: root/max_distance_closest_person.cpp
diff options
context:
space:
mode:
authorjack <0x6A73@pm.me>2024-06-14 13:13:15 -0600
committerjack <0x6A73@pm.me>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /max_distance_closest_person.cpp
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'max_distance_closest_person.cpp')
-rw-r--r--max_distance_closest_person.cpp39
1 files changed, 39 insertions, 0 deletions
diff --git a/max_distance_closest_person.cpp b/max_distance_closest_person.cpp
new file mode 100644
index 0000000..a9203fe
--- /dev/null
+++ b/max_distance_closest_person.cpp
@@ -0,0 +1,39 @@
+// 849. Maximize Distance to Closest Person
+#include "leetcode.h"
+
+/*
+ * given an array representing a row of 'seats' where 'seats[i] = 1' represents
+ * a person sitting in the i'th seat, and 'seats[i] = 0' represents that the
+ * i'th 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 maximised. return that
+ * maximum distance to the closest person.
+ */
+
+class Solution {
+public:
+ int maxDistToClosest(vector<int> &seats) {
+ int n = seats.size(), empty = 0, ans = 0, idx1 = -1, idx2 = -1;
+ for (int i = 0; i < n; i++) {
+ if (seats[i] == 1) {
+ empty = 0;
+ if (idx1 == -1)
+ idx1 = i;
+ idx2 = i;
+ } else {
+ empty++;
+ ans = max(ans, (empty + 1) / 2);
+ }
+ }
+ ans = max({ans, idx1, n - 1 - idx2});
+ return ans;
+ }
+};
+
+int main() {
+ Solution obj;
+ vector<int> s1 = {1, 0, 0, 0, 1, 0, 1}, s2 = {1, 0, 0, 0}, s3 = {0, 1};
+ printf("%d\n", obj.maxDistToClosest(s1)); // expect: 2
+ printf("%d\n", obj.maxDistToClosest(s2)); // expect: 3
+ printf("%d\n", obj.maxDistToClosest(s3)); // expect: 1
+}