![JAR search and dependency download from the Maven repository](/logo.png)
g0601_0700.s0638_shopping_offers.Solution.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
package g0601_0700.s0638_shopping_offers
// #Medium #Array #Dynamic_Programming #Bit_Manipulation #Backtracking #Bitmask #Memoization
// #2023_02_10_Time_195_ms_(100.00%)_Space_35.1_MB_(100.00%)
class Solution {
fun shoppingOffers(
price: List,
special: List>,
needs: List
): Int {
val map: MutableMap, Int> = HashMap()
shoppingOffersUtil(price, special, needs, map)
return map[needs]!!
}
private fun shoppingOffersUtil(
price: List,
special: List>,
needs: List,
map: MutableMap, Int>
): Int {
if (map.containsKey(needs)) {
return map[needs]!!
}
var ans = computePrice(price, needs)
for (i in special.indices) {
if (verify(special[i], needs)) {
ans = Math.min(
special[i][needs.size] +
shoppingOffersUtil(
price,
special,
updatedNeeds(needs, special[i]),
map
),
ans
)
}
}
map[needs] = ans
return (map[needs])!!
}
private fun updatedNeeds(needs: List, special: List): List {
val updatedNeeds: MutableList = ArrayList(needs)
for (i in needs.indices) {
updatedNeeds[i] = updatedNeeds[i] - special[i]
}
return updatedNeeds
}
private fun verify(special: List, needs: List): Boolean {
for (i in needs.indices) {
if (special[i] > needs[i]) {
return false
}
}
return true
}
private fun computePrice(price: List, needs: List): Int {
var ans = 0
for (i in needs.indices) {
ans += (needs[i] * price[i])
}
return ans
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy