1+ # Apply Operation to maximize Score
2+ import math
3+ from heapq import nlargest
4+ from collections import defaultdict
5+
6+ MOD = 10 ** 9 + 7
7+
8+ def count_prime_factors (n ):
9+ """Returns the number of distinct prime factors of n."""
10+ factors = set ()
11+ for i in range (2 , int (math .sqrt (n )) + 1 ):
12+ while n % i == 0 :
13+ factors .add (i )
14+ n //= i
15+ if n > 1 :
16+ factors .add (n )
17+ return len (factors )
18+
19+ def precompute_prime_scores (limit = 10 ** 5 ):
20+ """Precomputes the prime scores for numbers from 1 to limit."""
21+ prime_scores = [0 ] * (limit + 1 )
22+
23+ for i in range (2 , limit + 1 ):
24+ if prime_scores [i ] == 0 : # `i` is a prime
25+ for j in range (i , limit + 1 , i ):
26+ prime_scores [j ] += 1 # Mark multiples of `i`
27+
28+ return prime_scores
29+
30+ def maxScore (nums , k ):
31+ """Computes the maximum score using `k` operations."""
32+ prime_scores = precompute_prime_scores (max (nums ))
33+
34+ # Store elements as (prime_score, value, index)
35+ elements = []
36+
37+ for i , num in enumerate (nums ):
38+ elements .append ((prime_scores [num ], num , i ))
39+
40+ # Sort by (prime_score descending, value descending, index ascending)
41+ elements .sort (reverse = True , key = lambda x : (x [0 ], x [1 ], - x [2 ]))
42+
43+ # Take `k` highest scoring elements
44+ result = 1
45+ for _ , value , _ in elements [:k ]:
46+ result = (result * value ) % MOD
47+
48+ return result
0 commit comments