How to make an array non-decreasing with minimum operations

Day 43/100 Problem Statement : Given an array nums, you can perform the following operation any number of times: Select the adjacent pair with the minimum sum in nums. If multiple such pairs exist, choose the leftmost one. Replace the pair with their sum. Return the minimum number of operations needed to make the array non-decreasing. An array is said to be non-decreasing if each element is greater than or equal to its previous element (if it exists). Input: nums = [5,2,3,1] Output: 2 Solution : https://lnkd.in/g3Z6NQxN public int minimumPairRemoval(int[] nums) { int length = nums.length - 1; int count = 0; while(length > 0) { boolean increase = true; int minSum = Integer.MAX_VALUE; int minIndex = -1; for(int i = 0; i < length; i++) { if(nums[i] > nums[i + 1]) increase = false; if(nums[i] + nums[i + 1] < minSum) { minSum = nums[i] + nums[i + 1]; minIndex = i; } } if(increase) break; nums[minIndex] = minSum; for(int i = minIndex + 1; i < length; i++) nums[i] = nums[i + 1]; length--; count++; } return count; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF

To view or add a comment, sign in

Explore content categories