Skip to content

Commit eb2f206

Browse files
committed
add 2654
1 parent 67744e9 commit eb2f206

2 files changed

Lines changed: 62 additions & 2 deletions

File tree

javascript/LeetCode/math/2654.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* 2654. Minimum Number of Operations to Make All Array Elements Equal to 1
3+
*
4+
* GCD = 最大公因數」(Greatest Common Divisor)
5+
* 陣列元素可操作數次,選任一index i (0 <= i < nums.length - 1)並取得nums[i] or nums[i + 1]的GCD
6+
* 若可讓每個元素都=1的話,回傳1,否則-1
7+
*
8+
* @param {number[]} nums
9+
* @return {number}
10+
*/
11+
var minOperations = function(nums) {
12+
let g = 0,nums1 = 0;
13+
14+
function mygcd(x,y){
15+
// 求x & y 的最大公約數
16+
// x & y 可能是很大的數
17+
if (y === 0) {
18+
return x;
19+
}
20+
return mygcd(y, x % y);
21+
}
22+
23+
for(const a of nums) {
24+
if(a === 1) {
25+
nums1++;
26+
}
27+
g = mygcd(g,a);
28+
}
29+
if(nums1 > 0) {
30+
return nums.length - nums1;
31+
}
32+
if(g > 1) {
33+
return -1;
34+
}
35+
36+
let minLen = nums.length;
37+
for (let i = 0; i < nums.length; ++i) {
38+
let currentGcd = 0;
39+
for (let j = i; j < nums.length; ++j) {
40+
currentGcd = mygcd(currentGcd, nums[j]);
41+
if(currentGcd === 1) {
42+
minLen = Math.min(minLen, j - i + 1);
43+
break;
44+
}
45+
}
46+
}
47+
return minLen + nums.length - 2;
48+
49+
};
50+
// let nums = [2,6,3,4];
51+
// 4
52+
// Explanation: We can do the following operations:
53+
// - Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4].
54+
// - Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4].
55+
// - Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4].
56+
// - Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1].
57+
let nums = [1,1];
58+
// 0
59+
console.log(minOperations(nums));

javascript/index.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1079,9 +1079,10 @@ var findXSum = function(nums, k, x) {
10791079
// }
10801080

10811081
};
1082-
let nums = [1,1,2,2,3,4,2,3], k = 6, x = 2;
1082+
// let nums = [1,1,2,2,3,4,2,3], k = 6, x = 2;
10831083
// [6,10,12]
10841084
// For subarray [1, 1, 2, 2, 3, 4], only elements 1 and 2 will be kept in the resulting array. Hence, answer[0] = 1 + 1 + 2 + 2.
10851085
// For subarray [1, 2, 2, 3, 4, 2], only elements 2 and 4 will be kept in the resulting array. Hence, answer[1] = 2 + 2 + 2 + 4. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.
10861086
// For subarray [2, 2, 3, 4, 2, 3], only elements 2 and 3 are kept in the resulting array. Hence, answer[2] = 2 + 2 + 2 + 3 + 3.
1087-
console.log(findXSum(nums,k,x));
1087+
// console.log(findXSum(nums,k,x));
1088+

0 commit comments

Comments
 (0)