Build Array Where You Can Find The Maximum Exactly K Comparisons — LeetCode 1420 Python Solution

HardDynamic ProgrammingPrefix Sum
Problem
#1420
Pattern
Prefix Sum
Reading time
4 min

The problem

You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: arr has exactly n integers.

Example

Input
n = 2, m = 3, k = 1
Output
6
Explanation
The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]

Python solution

Python
class Solution:
    def numOfArrays(self, n: int, m: int, k: int) -> int:
        if k == 0:
            return 0
        dp = [[[0] * (m + 1) for _ in range(k + 1)] for _ in range(n + 1)]
        mod = 10**9 + 7
        for i in range(1, m + 1):
            dp[1][1][i] = 1
        for i in range(2, n + 1):
            for c in range(1, min(k + 1, i + 1)):
                for j in range(1, m + 1):
                    dp[i][c][j] = dp[i - 1][c][j] * j
                    for j0 in range(1, j):
                        dp[i][c][j] += dp[i - 1][c - 1][j0]
                        dp[i][c][j] %= mod
        ans = 0
        for i in range(1, m + 1):
            ans += dp[n][k][i]
            ans %= mod
        return ans

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons?
LeetCode 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons is rated Hard on LeetCode.
What topics does LeetCode 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons cover?
LeetCode 1420. Build Array Where You Can Find The Maximum Exactly K Comparisons is tagged Dynamic Programming and Prefix Sum 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