Skip to content

Commit 980c71f

Browse files
committed
[hackerrank] "Fraudulent Activity notifications" N·log(d) 구현
1 parent c7a2dd8 commit 980c71f

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package hackerrank.sorting
2+
3+
fun activityNotifications(expenditure: Array<Int>, d: Int): Int {
4+
var count = 0
5+
6+
(d until expenditure.size).forEach {
7+
if (isNotification(expenditure, it, d)) count++
8+
}
9+
10+
return count
11+
}
12+
13+
fun isNotification(
14+
expenditure: Array<Int>,
15+
index: Int,
16+
range: Int
17+
): Boolean {
18+
19+
val median = median(
20+
expenditure,
21+
index - range,
22+
index - 1
23+
)
24+
25+
return expenditure[index].toFloat() >= (median * 2f)
26+
}
27+
28+
private fun median(
29+
source: Array<Int>,
30+
from: Int,
31+
to: Int
32+
): Float {
33+
34+
val copy = source
35+
.copyOfRange(from, to + 1)
36+
.apply { sort() }
37+
38+
val mid = copy.size.div(2)
39+
40+
return if (copy.size.rem(2) == 0) {
41+
(copy[mid] + copy[mid + 1]).div(2f)
42+
} else {
43+
copy[mid].toFloat()
44+
}
45+
46+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package hackerrank.sorting
2+
3+
import org.junit.Assert.assertEquals
4+
import org.junit.Test
5+
6+
class FraudulentActivityNotificationsKtTest {
7+
8+
@Test
9+
fun activityNotifications() {
10+
assertEquals(2, activityNotifications(arrayOf(2, 3, 4, 2, 3, 6, 8, 4, 5), 5))
11+
assertEquals(0, activityNotifications(arrayOf(1, 2, 3, 4, 4), 4))
12+
}
13+
14+
}

0 commit comments

Comments
 (0)