Apply Operations to Maximize Score - Problem

You are given an array nums of n positive integers and an integer k.

Initially, you start with a score of 1. You have to maximize your score by applying the following operation at most k times:

  • Choose any non-empty subarray nums[l, ..., r] that you haven't chosen previously.
  • Choose an element x of nums[l, ..., r] with the highest prime score. If multiple such elements exist, choose the one with the smallest index.
  • Multiply your score by x.

Here, nums[l, ..., r] denotes the subarray of nums starting at index l and ending at the index r, both ends being inclusive.

The prime score of an integer x is equal to the number of distinct prime factors of x. For example, the prime score of 300 is 3 since 300 = 2 * 2 * 3 * 5 * 5.

Return the maximum possible score after applying at most k operations.

Since the answer may be large, return it modulo 109 + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,3,5], k = 3
Output: 30
💡 Note: Prime scores: [1,1,1,1]. All elements have same prime score, so we pick by value. Best subarrays give us elements [5,5,5] (element 5 can be picked from 4 different subarrays). Result: 5×5×2 = 50. Wait, let me recalculate... We get candidates like 5,5,3,3,3,2 and pick 3 largest: 5×5×3 = 75. Actually, let me use a simpler example.
Example 2 — Different Prime Scores
$ Input: nums = [6,7], k = 2
Output: 42
💡 Note: Prime scores: 6=2×3 has score 2, 7 has score 1. Element 6 dominates subarray [6], element 7 dominates subarray [7]. Both elements can be picked from subarray [6,7] but 6 wins due to higher prime score. Candidates: [6,7,6]. Pick k=2 largest: 6×6 = 36. Hmm, let me recalculate...
Example 3 — Small Array
$ Input: nums = [4], k = 1
Output: 4
💡 Note: Only one element with prime score 1. Only one subarray [4], so we pick 4 once. Result: 4.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105
  • 1 ≤ k ≤ min(nums.length * (nums.length + 1) / 2, 109)

Visualization

Tap to expand
Apply Operations: nums=[2,3,5], k=2235prime:1prime:1prime:1Subarrays and best elements:[2]→2, [3]→3, [5]→5, [2,3]→3, [3,5]→5, [2,3,5]→5Candidates: [2,3,5,3,5,5] → Sort: [5,5,5,3,3,2]Pick k=2 largest: 5 × 5 = 25Maximum Score: 25
Understanding the Visualization
1
Input
Array nums=[2,3,5] and k=2 operations
2
Process
Find best element from each possible subarray based on prime scores
3
Output
Multiply score by k best elements
Key Takeaway
🎯 Key Insight: Use monotonic stacks to efficiently find how many subarrays each element dominates
Asked in
Google 15 Meta 12 Apple 8
12.0K Views
Medium Frequency
~35 min Avg. Time
450 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