From b0a4c140be7da27337b1b1c045e6a4743e88924c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 12 Nov 2024 15:44:00 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB2070.=20Most=20Beautiful=20It?= =?UTF-8?q?em=20for=20Each=20Query=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/most-beautiful-item-for-each-query/ Signed-off-by: Matej Focko --- kt/most-beautiful-item-for-each-query.kt | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 kt/most-beautiful-item-for-each-query.kt 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() + } +}