Pizza With 3n Slices — LeetCode 1388 Python Solution

HardGreedyArrayDynamic ProgrammingHeap (Priority Queue)
Problem
#1388
Reading time
3 min

The problem

There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows: You will pick any pizza slice. Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.

Example

Input
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.

Python solution

Python
class Solution:
    def maxSizeSlices(self, slices: List[int]) -> int:
        def g(nums: List[int]) -> int:
            m = len(nums)
            f = [[0] * (n + 1) for _ in range(m + 1)]
            for i in range(1, m + 1):
                for j in range(1, n + 1):
                    f[i][j] = max(
                        f[i - 1][j], (f[i - 2][j - 1] if i >= 2 else 0) + nums[i - 1]
                    )
            return f[m][n]

        n = len(slices) // 3
        a, b = g(slices[:-1]), g(slices[1:])
        return max(a, b)

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n^2) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1388. Pizza With 3n Slices is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1388. Pizza With 3n Slices?
LeetCode 1388. Pizza With 3n Slices is rated Hard on LeetCode.
What is the time complexity of LeetCode 1388. Pizza With 3n Slices?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 1388. Pizza With 3n Slices?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 1388. Pizza With 3n Slices cover?
LeetCode 1388. Pizza With 3n Slices is tagged Greedy, Array, Dynamic Programming and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview