Solved #100DaysOfCode problem 2654 in Java with GCD logic

Day 40 of #100daysOfCode Problem: 2654. Minimum Number of Operations to Make All Array Elements Equal to 1 Difficulty: Medium Language: Java Status: Solved Problem Summary: You're given an array of positive integers nums. In one operation, you can choose an index i (where 0 ≤ i < n - 1) and replace either nums[i] or nums[i+1] with gcd(nums[i], nums[i+1]). You need to find the minimum number of operations to make all elements equal to 1. If it’s not possible, return -1. Key Insight: If there’s at least one 1 in the array → we can convert all other elements to 1 in n - count(1) operations. Otherwise, find the shortest subarray whose GCD = 1. Once found, it takes (j - i) operations to create one 1 and (n - 1) more to make the entire array 1. Algorithm Steps: Count how many elements are 1. If any exist → answer = n - ones. If not → iterate all subarrays, compute GCD until it becomes 1. Keep track of the smallest subarray length that reaches GCD = 1. If none found → return -1. Else return minLength + (n - 1). Time Complexity: O(n² * log(max(nums[i]))) Space Complexity: O(1) Learning Takeaway: Classic GCD reduction logic—search for minimal segment that can “spread” ones across the array. Efficiently reuses math logic in algorithmic reasoning. #Day40 #100DaysOfCode #LeetCode #Math #GCD #Greedy #Java #Algorithms #CodingChallenge #ProblemSolving #DSA

  • graphical user interface

To view or add a comment, sign in

Explore content categories