638.shopping-offers.go 736 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. func shoppingOffers(price []int, special [][]int, needs []int) int {
  2. var need [6]int
  3. copy(need[:], needs)
  4. m := make(map[[6]int]int)
  5. return buy(price, special, need, m) // DFS
  6. }
  7. func buy(price []int, special [][]int, need [6]int, m map[[6]int]int) int {
  8. if v, ok := m[need]; ok {
  9. return v
  10. }
  11. res := 0
  12. for i := range price {
  13. res += need[i] * price[i]
  14. } // The price without special offer
  15. for _, s := range special {
  16. var n [6]int
  17. copy(n[:], need[:])
  18. i := 0
  19. for ; i < len(price); i++ {
  20. n[i] -= s[i]
  21. if n[i] < 0 {
  22. break
  23. }
  24. }
  25. if i == len(price) {
  26. res = minInt(res, s[i]+buy(price, special, n, m))
  27. }
  28. }
  29. m[need] = res
  30. return res
  31. }
  32. func minInt(x, y int) int {
  33. if x < y {
  34. return x
  35. }
  36. return y
  37. }