Taro Logo

Divisible Game

#17 Most AskedMedium
0 views
Topics:
ArraysDynamic ProgrammingGreedy Algorithms

You are given an integer array nums of length n.

Alice and Bob are playing a game. Alice chooses:

  • An integer k such that k > 1.
  • Two integers l and r such that 0 <= l <= r < n.

Initially, both Alice's and Bob's scores are 0.

For each index i in the range [l, r] (inclusive):

  • If nums[i] is divisible by k, Alice's score increases by nums[i].
  • Otherwise, Bob's score increases by nums[i].

The score difference is Alice's score minus Bob's score.

Alice wants to maximize the score difference. If there are multiple values of k that achieve the maximum score difference, she chooses the smallest such k.

Return the product of the maximum score difference and the chosen value of k. Since the result can be large, return it modulo 109 + 7.

Example 1:

Input: nums = [1,4,6,8]

Output: 36

Explanation:

  • Alice can choose k = 2, l = 1, and r = 3.
  • All values in nums[1..3] are divisible by 2, so Alice's score is 4 + 6 + 8 = 18, while Bob's score is 0.
  • The score difference is 18, which is the maximum possible. Among all values of k that achieve this score difference, the smallest is 2.
  • Therefore, the answer is 18 * 2 = 36.

Example 2:

Input: nums = [2,1,2]

Output: 6

Explanation:

  • Alice can choose k = 2, l = 0, and r = 2.
  • The values nums[0] and nums[2] are divisible by 2, so Alice's score is 2 + 2 = 4. The value nums[1] is not divisible by 2, so Bob's score is 1.
  • The score difference is 4 - 1 = 3, which is the maximum possible. Among all values of k that achieve this score difference, the smallest is 2.
  • Therefore, the answer is 3 * 2 = 6.

Example 3:

Input: nums = [1]

Output: 1000000005

Explanation:

  • Alice must choose some k > 1. The smallest possible choice is k = 2.
  • Since nums[0] is not divisible by 2, Alice's score is 0, while Bob's score is 1.
  • The score difference is -1, which is the maximum possible.
  • Therefore, the answer is -1 * 2 = -2. Modulo 109 + 7, this equals 1000000005.

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 106

Solution


Brute Force Solution

Approach

The game requires selecting an integer divisor greater than one and a contiguous subarray to maximize the difference between Alice's and Bob's scores. For any chosen divisor, each element in the subarray contributes positively if it is divisible by the divisor and negatively otherwise, which reduces to finding the maximum subarray sum using Kadane's algorithm. Because any composite divisor is a multiple of a prime and divides at most the same elements, we only need to test prime factors of the numbers in the array along with the minimum valid divisor 2.

Here's how the algorithm would work step-by-step:

  1. Collect candidate divisors greater than one by finding prime factors of all array elements and including two.
  2. Sort the set of candidate divisors to ensure ties in the score difference are broken by choosing the smallest divisor.
  3. For each divisor, compute the maximum subarray sum where an element contributes positively if divisible and negatively otherwise.
  4. Track the maximum score difference across all candidate divisors and keep the smallest divisor that achieves it.
  5. Multiply the maximum score difference by the chosen divisor and return the result modulo 10^9 + 7.

Code Implementation

def divisible_game(nums):
    # Find all unique prime factors and candidate divisors greater than 1
    candidate_divisors = set([2])
    for number in nums:
        temp_val = number
        divisor = 2
        while divisor * divisor <= temp_val:
            if temp_val % divisor == 0:
                candidate_divisors.add(divisor)
                while temp_val % divisor == 0:
                    temp_val //= divisor
            divisor += 1
        if temp_val > 1:
            candidate_divisors.add(temp_val)

    best_difference = -float('inf')
    chosen_divisor = 2
    modulus = 10**9 + 7

    # Evaluate the maximum subarray score difference for each candidate divisor
    for divisor in sorted(candidate_divisors):
        current_sum = 0
        max_diff_for_divisor = -float('inf')
        for number in nums:
            score_contribution = number if number % divisor == 0 else -number
            current_sum = max(score_contribution, current_sum + score_contribution)
            if current_sum > max_diff_for_divisor:
                max_diff_for_divisor = current_sum

        # Update the overall best score difference and the chosen divisor
        if max_diff_for_divisor > best_difference:
            best_difference = max_diff_for_divisor
            chosen_divisor = divisor

    result = (best_difference * chosen_divisor) % modulus
    return result

Big(O) Analysis

Time Complexity
O(N * (sqrt(M) + P)) – Factoring each number up to M = 10^6 takes O(sqrt(M)) time. There are at most P distinct prime factors, and evaluating the maximum subarray sum for each candidate using Kadane's algorithm takes O(N) time.
Space Complexity
O(P) – A set is used to store all unique candidate prime divisors, which is at most a few thousand values given the constraints.

Optimal Solution

Approach

For a fixed divisor k, each element in the chosen subarray contributes positively if it is divisible by k and negatively otherwise. Finding the optimal subarray for a fixed k is equivalent to the maximum subarray sum problem, which can be solved using Kadane's algorithm. Because any element divisible by a composite number is also divisible by its prime factors, testing prime factors of elements alongside a default candidate suffices.

Here's how the algorithm would work step-by-step:

  1. Extract all prime factors of the numbers in the array to form a set of candidate divisors.
  2. Include the minimum allowed divisor, 2, in the candidate set to cover cases with no suitable prime factors.
  3. Sort the candidate divisors in ascending order to naturally break ties by choosing the smallest value of k.
  4. For each candidate, map each element of the array to a positive or negative score and apply Kadane's algorithm to compute the maximum subarray sum.
  5. Track the overall maximum score difference and record the smallest k that attains it.
  6. Compute the product of the best score difference and optimal k, returning the result modulo 10^9 + 7.

Code Implementation

def divisible_game(nums: list[int]) -> int:
    modulo = 10**9 + 7
    distinct_factors = set()
    # Find all prime factors and divisors greater than 1 from the array elements
    for value in nums:
        temp_val = value
        divisor = 2
        while divisor * divisor <= temp_val:
            if temp_val % divisor == 0:
                distinct_factors.add(divisor)
                while temp_val % divisor == 0:
                    temp_val //= divisor
            divisor += 1
        if temp_val > 1:
            distinct_factors.add(temp_val)
    
    # Always include 2 as a baseline candidate
    distinct_factors.add(2)
    candidate_list = sorted(distinct_factors)
    
    best_diff = -float('inf')
    best_k = 2
    
    # Evaluate the maximum subarray sum for each candidate divisor
    for candidate in candidate_list:
        current_max = -float('inf')
        running_sum = 0
        for num in nums:
            gain = num if num % candidate == 0 else -num
            running_sum = max(gain, running_sum + gain)
            if running_sum > current_max:
                current_max = running_sum
        
        # Update the best score difference and the minimal candidate
        if current_max > best_diff:
            best_diff = current_max
            best_k = candidate
            
    return (best_diff * best_k) % modulo

Big(O) Analysis

Time Complexity
O(N * sqrt(M) + C * N) – Factoring each number takes up to O(sqrt(M)) where M <= 10^6 is the maximum value in nums. Testing each of the C distinct prime factors across the array of length N takes O(C * N) time using Kadane's algorithm, which easily fits within the time limit.
Space Complexity
O(C) – We store the distinct prime factor candidates in a set and list, which takes O(C) additional space where C is bounded by the total number of distinct prime factors of numbers up to 10^6.

Edge Cases

Empty or single-element input arrays
How to Handle:
Return false immediately since no valid moves can be made by the first player.
Arrays containing duplicate numbers
How to Handle:
Treat each element distinctly by index or frequency to ensure proper state transitions during the game.
Inputs with zeros or negative numbers
How to Handle:
Filter out or safely handle zeros to avoid division by zero errors when checking divisibility rules.
Inputs with all pairwise coprime numbers
How to Handle:
Recognize that no moves are possible from the start, resulting in an immediate loss for the first player.
Maximum-sized input arrays leading to deep recursion or state explosion
How to Handle:
Use memoization or bottom-up dynamic programming to avoid redundant calculations and stack overflows.
Scores forming a strict chain of divisibility
How to Handle:
Simulate the deterministic elimination sequence to correctly determine the parity of the winning player.
0/257 completed