Minimize the Maximum Value of GCD-Connected Array Problem
Description
LeetCode Problem 4098.
You are given three integers n, index, and value.
An integer array nums of length n is called GCD-Connected if:
nums[i] > 0for0 <= i <= n - 1.nums[i] < nums[i + 1]for0 <= i <= n - 2.nums[index] = value.gcd(nums[i], nums[i + 1]) > 1for0 <= i <= n - 2.
Return the minimum possible maximum value, nums[n - 1], among all GCD-Connected arrays nums. If no such array exists, return -1.
Example 1:
Input: n = 4, index = 2, value = 8
Output: 10
Explanation:
- The GCD-Connected array will look like: nums = [?, ?, 8, ?] since nums[2] = 8.
- Since nums[3] > 8 and gcd(8, 9) = 1, every valid GCD-Connected array must have nums[3] >= 10.
- One optimal array satisfying all conditions is [2, 4, 8, 10].
- Thus, the minimum possible value of nums[3] is 10.
Example 2:
Input: n = 2, index = 1, value = 3
Output: -1
Explanation:
- The GCD-Connected array will look like: nums = [?, 3] since nums[1] = 3.
- Since we need 0 < nums[0] < nums[1] = 3, there are only two possible arrays: [1, 3] and [2, 3]. Neither of them satisfies gcd(nums[0], nums[1]) > 1.
- Therefore, no valid GCD-Connected array exists, and the answer is -1.
Example 3:
Input: n = 2, index = 0, value = 3
Output: 6
Explanation:
- The GCD-Connected array will look like: nums = [3, ?] since nums[0] = 3.
- Since nums[1] > 3 and gcd(3, 4) = gcd(3, 5) = 1, every valid GCD-Connected array must have nums[1] >= 6.
- One optimal array is [3, 6].
- Thus, the minimum possible value of nums[1] is 6.
Constraints:
2 <= n <= 10^91 <= value <= 10^90 <= index <= n - 1
Solution
Approach: Smallest Prime Factor and Greedy
If value = 1, then gcd(1, x) = 1 for every x, so return -1.
Otherwise let p be the smallest prime factor of value (found by trial division up to its square root; p = value if it is prime). A neighbor of value must share a factor with it, so it differs from value by at least p. Any other neighboring pair must be at least 2 apart. Since value and p have the same parity, value - p and value + p are even, and the remaining positions can all be even numbers stepping by 2.
- Left side. Make
nums[index - 1] = value - pand subtract 2 per step, sonums[0] = value - p - (index - 1) * 2. If that is at most 0 there is no room for positive integers, so return -1. (Forindex = 0there is nothing to the left.) - Right side. If
index = n - 1, the answer isvalue. Otherwisenums[index + 1] = value + pand each later element adds 2, givingvalue + p + (n - 2 - index) * 2.
Complexity: O(sqrt(value)) time and O(1) space. The answer can exceed 32 bits, so use a 64-bit integer.
from math import isqrt
class Solution:
def minimumMaxValue(self, n: int, index: int, value: int) -> int:
if value == 1:
return -1
p = value
for x in range(2, isqrt(value) + 1):
if value % x == 0:
p = x
break
if value - p - (index - 1) * 2 <= 0:
return -1
if index == n - 1:
return value
return value + p + (n - 2 - index) * 2