Problem Description
You are given an array of positive integers and an integer k. Starting with a score of 1, you can perform at most k operations. In each operation, you choose a non-empty subarray that has not been chosen before, then select the element from that subarray whose "prime score" (i.e. number of distinct prime factors) is the highest (if there is a tie, choose the one with the smallest index), and multiply your current score by that element. Return the maximum possible score modulo 10^9+7.
Key Insights
- Transforming the problem: Instead of simulating each subarray pick, count for each element the total number of subarrays where it would be chosen.
- Use monotonic stacks to efficiently calculate the “span” (left and right boundaries) where an element’s prime score is dominant.
- Compute the weight (frequency) for each element as the product of its left and right spans.
- Greedily multiplying by the largest numbers first maximizes the overall product.
- Use fast exponentiation and modular arithmetic to handle large exponents and mod operations.
Space and Time Complexity
Time Complexity: O(n log n), due to prime factorization for numbers up to 10^5 and sorting the candidate pairs. Space Complexity: O(n), for storing prime scores, spans, and candidate pairs.
Solution
- Precompute the smallest prime factors (spf) for all numbers up to the maximum value in the array using the sieve method.
- For each number in the array, calculate its prime score (the number of distinct prime factors).
- Use two monotonic stacks to compute for every element its left and right spans:
- Left span indicates the number of subarrays ending at the current element where it is the dominant candidate.
- Right span indicates the number of subarrays starting at the current element where it remains dominant.
- The frequency (number of subarrays where an element is chosen) is the product of its left and right spans.
- Create a list of (value, frequency) pairs and sort them in descending order by value.
- Iterate through the list and greedily “use” each element as many times as possible (up to its frequency or remaining operations k), multiplying the result accordingly (using fast modular exponentiation).
- Return the final score modulo 10^9+7.