diff --git a/kt/most-beautiful-item-for-each-query.kt b/kt/most-beautiful-item-for-each-query.kt new file mode 100644 index 0000000..4ddeff6 --- /dev/null +++ b/kt/most-beautiful-item-for-each-query.kt @@ -0,0 +1,33 @@ +class Solution { + private data class Item(val price: Int, val beauty: Int) + + fun maximumBeauty( + items: Array, + 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() + } +}