2025-11-12 Daily Challenge
Today I have done leetcode's November LeetCoding Challenge with cpp.
November LeetCoding Challenge 12
Description
Minimum Number of Operations to Make All Array Elements Equal to 1
You are given a 0-indexed array nums consisiting of positive integers. You can do the following operation on the array any number of times:
- Select an index
isuch that0 <= i < n - 1and replace either ofnums[i]ornums[i+1]with their gcd value.
Return the minimum number of operations to make all elements of nums equal to 1. If it is impossible, return -1.
The gcd of two integers is the greatest common divisor of the two integers.
Example 1:
Input: nums = [2,6,3,4] Output: 4 Explanation: We can do the following operations: - Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4]. - Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4]. - Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4]. - Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1].
Example 2:
Input: nums = [2,10,6,14] Output: -1 Explanation: It can be shown that it is impossible to make all the elements equal to 1.
Constraints:
2 <= nums.length <= 501 <= nums[i] <= 106
Solution
int gcd(int a, int b) {
return b ? gcd(b, a % b) : a;
}
class Solution {
public:
int minOperations(vector<int>& nums) {
int n = nums.size();
int answer = INT_MAX;
int ones = 0;
for(int i = 0; i < n; ++i) {
if(nums[i] == 1) ones += 1;
}
if(ones) return n - ones;
for(int i = 0; i < n; ++i) {
int g = nums[i];
for(int j = i + 1; j < n; ++j) {
g = gcd(g, nums[j]);
if(g != 1) continue;
answer = min(answer, j - i + n - 1);
break;
}
}
return answer == INT_MAX ? -1 : answer;
}
};
// Accepted
// 1068/1068 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 93.06 % of cpp submissions (31.5 MB)