kt: add «2070. Most Beautiful Item for Each Query»

URL:	https://leetcode.com/problems/most-beautiful-item-for-each-query/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-11-12 15:44:00 +01:00
parent d2aca8d88f
commit b0a4c140be
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,33 @@
class Solution {
private data class Item(val price: Int, val beauty: Int)
fun maximumBeauty(
items: Array<IntArray>,
queries: IntArray,
): IntArray {
// Sort items by the price
val items = items.map { Item(it[0], it[1]) }.toMutableList()
items.sortBy { it.price }
val maxBeautyTillNow =
items.scan(0) { runningMax, it ->
listOf(runningMax, it.beauty).max()
}
// Sort queries by the price
val sortedQueries = queries.withIndex().toMutableList()
sortedQueries.sortBy { it.value }
var i = 0
return sortedQueries.map { query ->
while (i < items.size && items[i].price <= query.value) {
i += 1
}
IndexedValue(query.index, maxBeautyTillNow[i])
}.sortedBy { query ->
query.index
}.map { query ->
query.value
}.toIntArray()
}
}