Skip to content

Commit ee2d53a

Browse files
authored
Create 2483-minimum-penalty-for-a-shop.kt
1 parent f81926d commit ee2d53a

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
}

0 commit comments

Comments
 (0)