LeetCode-in-Java

3984. Divisible Game

Medium

You are given an integer array nums of length n.

Alice and Bob are playing a game. Alice chooses:

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

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

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:

Example 2:

Input: nums = [2,1,2]

Output: 6

Explanation:

Example 3:

Input: nums = [1]

Output: 1000000005

Explanation:

Constraints:

Solution

import java.util.HashSet;

public class Solution {
    public int divisibleGame(int[] nums) {
        HashSet<Integer> prime = new HashSet<>();
        int mod = (int) 1e9 + 7;
        long bestscore = nums[0];
        for (int i : nums) {
            bestscore = Math.min(bestscore, i);
        }
        bestscore = -bestscore;
        long bestprime = 2;
        for (int i : nums) {
            for (int j = 2; j * j <= i; j++) {
                if (i % j == 0) {
                    prime.add(j);
                    while (i % j == 0) {
                        i = i / j;
                    }
                }
            }
            if (i > 1) {
                prime.add(i);
            }
        }
        for (int p : prime) {
            long curr = 0;
            long maxi = Long.MIN_VALUE;
            for (int i : nums) {
                long val = (i % p == 0) ? i : -i;
                curr = Math.max(0, curr + val);
                maxi = Math.max(maxi, curr);
            }
            if (maxi > bestscore) {
                bestscore = maxi;
                bestprime = p;
            } else if (maxi == bestscore && p < bestprime) {
                bestprime = p;
            }
        }
        bestscore = ((bestscore % mod) + mod) % mod;
        return (int) ((bestscore * (bestprime % mod)) % mod);
    }
}