|
| 1 | +/** |
| 2 | + * 1388. Pizza With 3n Slices |
| 3 | + * https://leetcode.com/problems/pizza-with-3n-slices/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There is a pizza with 3n slices of varying size, you and your friends will take slices |
| 7 | + * of pizza as follows: |
| 8 | + * - You will pick any pizza slice. |
| 9 | + * - Your friend Alice will pick the next slice in the anti-clockwise direction of your pick. |
| 10 | + * - Your friend Bob will pick the next slice in the clockwise direction of your pick. |
| 11 | + * - Repeat until there are no more slices of pizzas. |
| 12 | + * |
| 13 | + * Given an integer array slices that represent the sizes of the pizza slices in a clockwise |
| 14 | + * direction, return the maximum possible sum of slice sizes that you can pick. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[]} slices |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var maxSizeSlices = function(slices) { |
| 22 | + const n = slices.length; |
| 23 | + const count = n / 3; |
| 24 | + const case1 = selectMaxSum(slices, count - 1, 2, n - 2); |
| 25 | + const case2 = selectMaxSum(slices, count, 1, n - 1); |
| 26 | + |
| 27 | + return Math.max(slices[0] + case1, case2); |
| 28 | + |
| 29 | + function selectMaxSum(arr, count, start, end, memo = new Map()) { |
| 30 | + const key = `${count},${start},${end}`; |
| 31 | + if (count === 0 || start > end) return 0; |
| 32 | + if (memo.has(key)) return memo.get(key); |
| 33 | + |
| 34 | + const includeFirst = arr[start] + selectMaxSum(arr, count - 1, start + 2, end, memo); |
| 35 | + const excludeFirst = selectMaxSum(arr, count, start + 1, end, memo); |
| 36 | + const result = Math.max(includeFirst, excludeFirst); |
| 37 | + |
| 38 | + memo.set(key, result); |
| 39 | + return result; |
| 40 | + } |
| 41 | +}; |
0 commit comments