Skip to content

Commit 28b757c

Browse files
add 2231
1 parent c6e6b24 commit 28b757c

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

contest/src/main/java/com/github/contest/Execute.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.github.contest
22

33

4-
import com.github.contest.dp.maxAbsoluteSum
4+
import com.github.contest.heap.largestInteger
55
import java.util.TreeMap
66

77

@@ -11,7 +11,7 @@ import java.util.TreeMap
1111

1212
fun main() {
1313

14-
maxAbsoluteSum(intArrayOf(1, -3, 2, 3, -4)).also { println(it) }
14+
largestInteger(1234)
1515

1616
}
1717

contest/src/main/java/com/github/contest/heap/HeapLeetcode.kt

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,3 +310,46 @@ fun maxSubsequence(nums: IntArray, k: Int): IntArray {
310310

311311
return indices.map { it.first }.toIntArray()
312312
}
313+
314+
/**
315+
* 2231. Largest Number After Digit Swaps by Parity
316+
*/
317+
318+
319+
fun largestInteger(num: Int): Int {
320+
val s = num.toString()
321+
val n = s.length
322+
val odd = mutableListOf<Int>()
323+
val even = mutableListOf<Int>()
324+
val oddIndices = mutableListOf<Int>()
325+
val evenIndices = mutableListOf<Int>()
326+
327+
for (i in 0 until n) {
328+
val digit = s[i] - '0'
329+
if (digit % 2 == 0) {
330+
even.add(digit)
331+
evenIndices.add(i)
332+
} else {
333+
odd.add(digit)
334+
oddIndices.add(i)
335+
}
336+
}
337+
338+
odd.sortDescending()
339+
even.sortDescending()
340+
341+
val result = CharArray(n)
342+
var oddIndex = 0
343+
var evenIndex = 0
344+
345+
for (i in 0 until n) {
346+
if (s[i].toInt() % 2 == 0) {
347+
result[i] = (even[evenIndex++]).toChar() + '0'.toInt()
348+
} else {
349+
result[i] = (odd[oddIndex++]).toChar() + '0'.toInt()
350+
}
351+
}
352+
353+
return String(result).toInt()
354+
}
355+

0 commit comments

Comments
 (0)