HardNo. 2518

Number of Great Partitions — LeetCode 2518 Python Solution

Topics
Array, Dynamic Programming
Reading time
3 min

The problem

You are given an array nums consisting of positive integers and an integer k. Partition the array into two ordered groups such that each element is in exactly one group.

Example

Input
nums = [1,2,3,4], k = 4
Output
6
Explanation
The great partitions are: ([1,2,3], [4]), ([1,3], [2,4]), ([1,4], [2,3]), ([2,3], [1,4]), ([2,4], [1,3]) and ([4], [1,2,3]).

Python solution

PythonSolution
class Solution:
    def countPartitions(self, nums: List[int], k: int) -> int:
        if sum(nums) < k * 2:
            return 0
        mod = 10**9 + 7
        n = len(nums)
        f = [[0] * k for _ in range(n + 1)]
        f[0][0] = 1
        ans = 1
        for i in range(1, n + 1):
            ans = ans * 2 % mod
            for j in range(k):
                f[i][j] = f[i - 1][j]
                if j >= nums[i - 1]:
                    f[i][j] = (f[i][j] + f[i - 1][j - nums[i - 1]]) % mod
        return (ans - sum(f[-1]) * 2 + mod) % mod

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2518. Number of Great Partitions is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium
0085Maximal RectangleHard

Frequently asked questions

How hard is LeetCode 2518. Number of Great Partitions?

LeetCode 2518. Number of Great Partitions is rated Hard on LeetCode.

What topics does LeetCode 2518. Number of Great Partitions cover?

LeetCode 2518. Number of Great Partitions is tagged Array and Dynamic Programming 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.