Build Array Where You Can Find The Maximum Exactly K Comparisons - Problem

You are given three integers n, m, and k. You need to build an array arr of exactly n integers where each integer is between 1 and m (inclusive).

Consider an algorithm that finds the maximum element by scanning the array from left to right. The algorithm counts how many times it finds a new maximum (including the first element). This count is called the search cost.

Your task is to count how many different arrays have a search cost of exactly k. Since the answer can be very large, return it modulo 10^9 + 7.

Example: For array [3, 1, 4, 2], the search cost is 2 because we find new maximums at positions 0 (value 3) and 2 (value 4).

Input & Output

Example 1 — Basic Case
$ Input: n = 2, m = 3, k = 1
Output: 6
💡 Note: Arrays with exactly 1 search cost: [1,1], [2,1], [2,2], [3,1], [3,2], [3,3]. Each has only the first element as a new maximum.
Example 2 — Multiple Peaks
$ Input: n = 3, m = 2, k = 2
Output: 6
💡 Note: Arrays: [1,2,1], [1,2,2], [2,1,2] have cost 2. We need exactly 2 new maximums found during the scan.
Example 3 — Edge Case
$ Input: n = 1, m = 1, k = 1
Output: 1
💡 Note: Only one array possible: [1]. It has exactly 1 search cost (the first element).

Constraints

  • 1 ≤ n ≤ 50
  • 1 ≤ m ≤ 100
  • 1 ≤ k ≤ n

Visualization

Tap to expand
Build Array with Exactly K Comparisons INPUT n=2 m=3 k=1 Array length: 2 elements Values: 1 to 3 Search cost: exactly 1 arr[0] arr[1] Search cost = times we find a NEW maximum Example: [3,1] 3 is first max (cost=1) 1 is not new max Total cost = 1 [OK] ALGORITHM STEPS 1 Define DP State dp[i][j][c] = arrays of len i, max j, cost c 2 Base Case dp[1][j][1] = 1 for all j from 1 to m 3 Transition Keep max: add val <= max New max: cost increases 4 Sum Results Answer = sum of dp[n][j][k] for all j DP Table (n=2, k=1) max=1: [1,1] = 1 way max=2: [2,1],[2,2] = 2 ways max=3: [3,1],[3,2],[3,3]=3 Total: 1+2+3 = 6 FINAL RESULT Output: 6 Valid Arrays (cost=1): [1, 1] [2, 1] [2, 2] [3, 1] [3, 2] [3, 3] All arrays have search cost = 1 (one max found) Verification [1,1]: max at pos 0 only [2,1]: 2 is max, 1 is not [3,3]: 3 at pos 0, same max All have cost=1 [OK] Key Insight: Use 3D DP where dp[i][j][c] counts arrays of length i with maximum value j and search cost c. Two transitions: (1) append value <= current max (cost unchanged), or (2) append new maximum (cost +1). Time: O(n * m^2 * k). The first element always contributes 1 to search cost. TutorialsPoint - Build Array Where You Can Find The Maximum Exactly K Comparisons | Dynamic Programming
Asked in
Google 15 Microsoft 8
23.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen