HardNo. 1388

Pizza With 3n Slices — LeetCode 1388 Python Solution

Topics
Greedy, Array, Dynamic Programming, Heap (Priority Queue)
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

PythonSolution
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

Time
O(n2)
Space · auxiliary
O(n2)

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

Related problems
No.ProblemDifficulty
0871Minimum Number of Refueling StopsHard
0045Jump Game IIMedium
0055Jump GameMedium
0122Best Time to Buy and Sell Stock IIMedium
0376Wiggle SubsequenceMedium
0435Non-overlapping IntervalsMedium

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(n2).

What is the space complexity of LeetCode 1388. Pizza With 3n Slices?

The Python solution on this page uses O(n2) 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.

Free to download. Check it runs on your machine, then pick a plan.