Skip to content

Commit 363d576

Browse files
committed
Add 2070. Most Beautiful Item for Each Query
1 parent d3c07db commit 363d576

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package sierikov.leetcode.tasks.medium
2+
3+
import sierikov.leetcode.tasks.easy.ConvertSortedListToBinarySearchTree.sortedListToBST
4+
5+
// leetcode: https://leetcode.com/problems/most-beautiful-item-for-each-query/
6+
object MostBeautifulItemForEachQuery {
7+
def maximumBeauty(items: Array[Array[Int]], queries: Array[Int]): Array[Int] = {
8+
9+
val sortedItems = items.sortBy(_.head) // sort by price
10+
var max = sortedItems(0)(1) // first beauty
11+
12+
for (i <- sortedItems.indices) {
13+
max = math.max(max, sortedItems(i)(1))
14+
sortedItems(i)(1) = max
15+
}
16+
17+
val ans = Array.ofDim[Int](queries.length)
18+
for (i <- queries.indices) {
19+
ans(i) = binarySearch(sortedItems, queries(i))
20+
}
21+
22+
ans
23+
}
24+
25+
private def binarySearch(items: Array[Array[Int]], targetPrice: Int): Int = {
26+
var l = 0
27+
var r = items.length - 1
28+
var maxBeauty = 0
29+
while (l <= r) {
30+
val mid = (l + r) / 2
31+
if (items(mid)(0) > targetPrice) {
32+
r = mid - 1
33+
} else {
34+
// Found viable price. Keep moving to right
35+
maxBeauty = math.max(maxBeauty, items(mid)(1))
36+
l = mid + 1
37+
}
38+
}
39+
maxBeauty
40+
}
41+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package sierikov.leetcode.tasks.medium
2+
3+
import org.scalatest.flatspec.AnyFlatSpec
4+
import org.scalatest.matchers.should.Matchers
5+
6+
class MostBeautifulItemForEachQueryTest extends AnyFlatSpec with Matchers {
7+
import MostBeautifulItemForEachQuery._
8+
9+
it should "find query correctly" in {
10+
val items = Array(Array(1, 2), Array(3, 2), Array(2, 4), Array(5, 6), Array(3, 5))
11+
val queries = Array(1, 2, 3, 4, 5, 6)
12+
13+
maximumBeauty(items, queries) shouldBe Array(2, 4, 5, 5, 6, 6)
14+
}
15+
16+
}

0 commit comments

Comments
 (0)