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 Exact Search Cost k=2Example: Array [1, 3, 2, 1] - Find peaks while scanning left to right1321Peak 1Peak 2≤ max≤ maxScan: 1 (new max) → 3 (new max) → 2 (≤3) → 1 (≤3)Search Cost = 2 peaks found ✓Goal: Count all arrays with exactly k=2 search costUse DP to efficiently count without generating all arrays
Understanding the Visualization
1
Input
Given n=4, m=3, k=2 (build array of length 4, values 1-3, exactly 2 peaks)
2
Process
Find arrays where scanning left-to-right finds exactly 2 new maximums
3
Output
Count all valid arrays (e.g., [1,3,2,1] has peaks at positions 0,1)
Key Takeaway
🎯 Key Insight: Use 3D DP to track position, current maximum, and remaining peaks needed
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