There is a pizza with 3n
slices of varying size, you and your friends will take slices of pizza as follows:
Given an integer array slices
that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.
Example 1:
slices = [1,2,3,4,5,6]
Output: 10
Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.
Example 2:
slices = [8,9,8,6,1,1]
Output: 16
Explanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.
Constraints:
3 * n == slices.length
1 <= slices.length <= 500
1 <= slices[i] <= 1000
We are given a circular array slices
representing the sizes of pizza slices. We need to pick slices such that no two adjacent slices are picked (due to Alice and Bob picking adjacent slices). The goal is to maximize the total size of the slices we pick.
A brute-force approach would involve trying all possible combinations of picking slices such that no two adjacent slices are picked. However, this approach is highly inefficient due to the exponential number of combinations. It would involve recursion and backtracking, leading to a time complexity of roughly O(2^n), where n is the number of slices.
Due to its time complexity, this approach is not suitable for the given constraints.
We can solve this problem using dynamic programming. Since the pizza is circular, we can consider two cases:
For each case, we can use dynamic programming to find the maximum sum of slice sizes we can pick without picking adjacent slices.
Let dp[i][j]
be the maximum sum we can get by picking j
slices from the first i
slices.
The recurrence relation is as follows:
dp[i][j] = max(dp[i-1][j], slices[i] + dp[i-2][j-1])
where dp[i-1][j]
represents not picking the i
th slice, and slices[i] + dp[i-2][j-1]
represents picking the i
th slice. If we pick i
th slice, we cannot pick i-1
th slice, so we look back to i-2
th slice and pick j-1
slices.
maxSlices(slices)
that takes the array of slice sizes as input.def maxSlices(slices):
n = len(slices)
k = n // 3
def solve(arr):
dp = [[0] * (k + 1) for _ in range(len(arr) + 1)]
for i in range(1, len(arr) + 1):
for j in range(1, k + 1):
dp[i][j] = max(dp[i-1][j], arr[i-1] + (dp[i-2][j-1] if i > 1 else 0))
return dp[len(arr)][k]
case1 = solve(slices[:-1])
case2 = solve(slices[1:])
return max(case1, case2)