> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Apply Operations to Maximize Score

> Tested Python solution for LeetCode 2818 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 2818, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Math](/catalog/topics/math), [Stack](/catalog/topics/stack), [Greedy](/catalog/topics/greedy), [Sorting](/catalog/topics/sorting), [Monotonic Stack](/catalog/topics/monotonic-stack), [Number Theory](/catalog/topics/number-theory). [View on LeetCode](https://leetcode.com/problems/apply-operations-to-maximize-score/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 2818   # by problem number
lcpy gen -s apply_operations_to_maximize_score   # by problem name
```

## 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

```
Input: nums = [8,3,9,3,8], k = 2
Output: 81
Explanation: To get a score of 81, we can apply the following operations:
- Choose subarray nums[2, ..., 2]. nums[2] is the only element in this subarray. Hence, we multiply the score by nums[2]. The score becomes 1 * 9 = 9.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 1, but nums[2] has the smaller index. Hence, we multiply the score by nums[2]. The score becomes 9 * 9 = 81.
It can be proven that 81 is the highest score one can obtain.
```

```
Input: nums = [19,12,14,6,10,18], k = 3
Output: 4788
Explanation: To get a score of 4788, we can apply the following operations:
- Choose subarray nums[0, ..., 0]. nums[0] is the only element in this subarray. Hence, we multiply the score by nums[0]. The score becomes 1 * 19 = 19.
- Choose subarray nums[5, ..., 5]. nums[5] is the only element in this subarray. Hence, we multiply the score by nums[5]. The score becomes 19 * 18 = 342.
- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 2, but nums[2] has the smaller index. Hence, we multipy the score by nums[2]. The score becomes 342 * 14 = 4788.
It can be proven that 4788 is the highest score one can obtain.
```

### 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](https://github.com/wislertt/leetcode-py/blob/main/leetcode/apply_operations_to_maximize_score/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/apply_operations_to_maximize_score/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
LIMIT = 100001


def _smallest_prime_factors() -> list[int]:
    spf = list(range(LIMIT))
    for i in range(2, int(LIMIT**0.5) + 1):
        if spf[i] == i:
            for j in range(i * i, LIMIT, i):
                if spf[j] == j:
                    spf[j] = i
    return spf


class Solution:
    # Time: O(n log n + max(nums) log log max(nums))
    # Space: O(max(nums))
    def maximum_score(self, nums: list[int], k: int) -> int:
        mod = 1_000_000_007
        spf = _smallest_prime_factors()

        def prime_score(x: int) -> int:
            count, cur = 0, x
            while cur > 1:
                p = spf[cur]
                count += 1
                while cur % p == 0:
                    cur //= p
            return count

        n = len(nums)
        scores = [prime_score(num) for num in nums]

        left = [-1] * n
        stack: list[int] = []
        for i in range(n):
            while stack and scores[stack[-1]] < scores[i]:
                stack.pop()
            left[i] = stack[-1] if stack else -1
            stack.append(i)

        right = [n] * n
        stack = []
        for i in range(n - 1, -1, -1):
            while stack and scores[stack[-1]] <= scores[i]:
                stack.pop()
            right[i] = stack[-1] if stack else n
            stack.append(i)

        result = 1
        remaining = k
        candidates = sorted(
            ((nums[i], (i - left[i]) * (right[i] - i)) for i in range(n)), reverse=True
        )
        for value, count in candidates:
            if remaining <= 0:
                break
            use = min(remaining, count)
            result = result * pow(value, use, mod) % mod
            remaining -= use
        return result
```

## Complexity

| Time | Space |
| - | - |
| O(n log n + max(nums) log log max(nums)) | O(max(nums)) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.