Min Operations to Make All Elements Equal to 1

Day 58/100 Problem Statement : 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 i such that 0 <= i < n - 1 and replace either of nums[i] or nums[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. Input: nums = [2,6,3,4] Output: 4 Solution : https://lnkd.in/eaD3v_XT public int minOperations(int[] nums) { int n = nums.length; int ones = 0; for (int x : nums) { if (x == 1) ones++; } if (ones > 0) return n - ones; int ans = Integer.MAX_VALUE; 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) { ans = Math.min(ans, j - i); break; } } } if (ans == Integer.MAX_VALUE) return -1; return ans + n - 1; } private int gcd(int a, int b) { while (b != 0) { int t = a % b; a = b; b = t; } return a; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF

To view or add a comment, sign in

Explore content categories