File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time O(n) and space O(n) with prefix/suffix sums
2
+ class Solution {
3
+ fun bestClosingTime (c : String ): Int {
4
+ val n = c.length
5
+ val prefix = IntArray (n + 1 )
6
+ val postfix = IntArray (n + 1 )
7
+
8
+ for (i in 1 .. n) {
9
+ prefix[i] = prefix[i - 1 ] + if (c[i - 1 ] == ' N' ) 1 else 0
10
+ }
11
+
12
+ for (i in n - 1 downTo 0 ) {
13
+ postfix[i] = postfix[i + 1 ] + if (c[i] == ' Y' ) 1 else 0
14
+ }
15
+
16
+ var res = Integer .MAX_VALUE
17
+ var min = Integer .MAX_VALUE
18
+ for (i in 0 .. n) {
19
+ val pen = prefix[i] + postfix[i]
20
+ if (pen < min) {
21
+ min = pen
22
+ res = i
23
+ }
24
+ }
25
+
26
+ return res
27
+ }
28
+ }
29
+
30
+ // Time O(n) and space O(1) with Kadane's Algorithm
31
+ class Solution {
32
+ fun bestClosingTime (customers : String ): Int {
33
+ var cur = 0
34
+ var max = 0
35
+ var closeTime = 0
36
+
37
+ for ((i, c) in customers.withIndex()) {
38
+ cur + = if (c == ' Y' ) 1 else - 1
39
+ if (cur > max) {
40
+ max = cur
41
+ closeTime = i + 1
42
+ }
43
+ }
44
+
45
+ return closeTime
46
+ }
47
+ }
You can’t perform that action at this time.
0 commit comments