#2818

Apply Operations to Maximize Score

Hard
ArrayMathStackGreedySortingMonotonic StackNumber TheoryGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

In the optimal approach, we first calculate the prime scores for each number and then use a greedy strategy to select the top k elements based on their prime scores. This reduces the number of operations significantly by focusing only on the highest prime scores.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the prime score for each element in the array.
  2. 2Step 2: Create a list of pairs (prime score, index) and sort it in descending order based on prime scores.
  3. 3Step 3: Select the first k elements from the sorted list and multiply their corresponding nums values to get the maximum score.
solution.py26 lines
1# Full working Python code
2from math import isqrt
3
4MOD = 10**9 + 7
5
6def prime_score(x):
7    score = 0
8    for i in range(2, isqrt(x) + 1):
9        if x % i == 0:
10            score += 1
11            while x % i == 0:
12                x //= i
13    if x > 1:
14        score += 1
15    return score
16
17def max_score(nums, k):
18    scores = [(prime_score(num), i) for i, num in enumerate(nums)]
19    scores.sort(reverse=True, key=lambda x: (x[0], -x[1]))
20    max_product = 1
21    for i in range(k):
22        max_product = (max_product * nums[scores[i][1]]) % MOD
23    return max_product
24
25# Example usage
26print(max_score([8, 3, 9, 3, 8], 2))  # Output: 81

Complexity note: This complexity comes from sorting the scores, which is much more efficient than evaluating all subarrays.

  • 1The prime score is crucial in determining which elements to select.
  • 2Sorting the elements based on their prime scores allows for efficient selection.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.