File tree Expand file tree Collapse file tree 1 file changed +39
-1
lines changed Expand file tree Collapse file tree 1 file changed +39
-1
lines changed Original file line number Diff line number Diff line change 1+ // 1. O(nlogn) solution using sorting
12class Solution {
23 fun maximumElementAfterDecrementingAndRearranging (arr : IntArray ): Int {
34 arr.sort()
@@ -11,8 +12,45 @@ class Solution {
1112 }
1213}
1314
14- // same as above but using Kotlin's Aggregate operation fold()
15+ // 2. O(n) solution but at the cost of O(1) -> O(n) space
16+ class Solution {
17+ fun maximumElementAfterDecrementingAndRearranging (arr : IntArray ): Int {
18+ val n = arr.size
19+ var count = IntArray (n + 1 ).apply {
20+ for (num in arr)
21+ this [minOf(n, num)]++
22+ }
23+
24+ var last = 1
25+ for (num in 1 .. n)
26+ last = minOf(last + count[num], num)
27+
28+ return last
29+ }
30+ }
31+
32+ // 3. Same as solution 1, but using Kotlin's Aggregate operation fold()
1533class Solution {
1634 fun maximumElementAfterDecrementingAndRearranging (arr : IntArray ) = arr.sorted()
1735 .fold(0 ) { acc, num -> minOf(acc + 1 , num) }
1836}
37+
38+ // 4. Or alternativly, we could use a runningFold()
39+ class Solution {
40+ fun maximumElementAfterDecrementingAndRearranging (arr : IntArray ) = arr.sorted()
41+ .runningFold (0 ) { acc, num -> minOf(acc + 1 , num) }
42+ .last()
43+ }
44+
45+ // 5. Same logic as first solution, but using a minHeap instead of sorting
46+ class Solution {
47+ fun maximumElementAfterDecrementingAndRearranging (arr : IntArray ) = with (PriorityQueue <Int >()) {
48+ addAll(arr.asSequence())
49+ var last = 0
50+ while (isNotEmpty()) {
51+ if (poll() > last)
52+ last++
53+ }
54+ last
55+ }
56+ }
You can’t perform that action at this time.
0 commit comments