Skip to main content
LeetCode 2818, Hard. Topics: Array, Math, Stack, Greedy, Sorting, Monotonic Stack, Number Theory. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:

Problem

<p>You are given an array <code>nums</code> of <code>n</code> positive integers and an integer <code>k</code>.</p> <p>Initially, you start with a score of <code>1</code>. You have to maximize your score by applying the following operation at most <code>k</code> times:</p> <ul> <li>Choose any <strong>non-empty</strong> subarray <code>nums[l, …, r]</code> that you haven’t chosen previously.</li> <li>Choose an element <code>x</code> of <code>nums[l, …, r]</code> with the highest <strong>prime score</strong>. If multiple such elements exist, choose the one with the smallest index.</li> <li>Multiply your score by <code>x</code>.</li> </ul> <p>Here, <code>nums[l, …, r]</code> denotes the subarray of <code>nums</code> starting at index <code>l</code> and ending at the index <code>r</code>, both ends being inclusive.</p> <p>The <strong>prime score</strong> of an integer <code>x</code> is equal to the number of distinct prime factors of <code>x</code>. For example, the prime score of <code>300</code> is <code>3</code> since <code>300 = 2 * 2 * 3 * 5 * 5</code>.</p> <p>Return <em>the <strong>maximum possible score</strong> after applying at most </em><code>k</code><em> operations</em>.</p> <p>Since the answer may be large, return it modulo <code>10<sup>9 </sup>+ 7</code>.</p>

Examples

Constraints

  • 1 <= nums.length == n <= 10^5
  • 1 <= nums[i] <= 10^5
  • 1 <= k <= min(n * (n + 1) / 2, 10^9)

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026