Find the minimised number using given operations
Given an array arr[] of n elements. In one operation you can pick two indices i and j, such that arr[i] ≥ arr[j] and replace the value of arr[i] with (arr[i] – arr[j]), the task is to minimize the values of the array after performing any number of such operations.
Examples:
Input: n = 3, arr[] = {3, 2, 4}
Output: 1
Explanation:
- 1st Operation: We can pick 4 & 3, subtract 4-3 => {3, 2, 1}
- 2nd Operation: We can pick 3 & 2, subtract 3-2 => {1, 2, 1}
- 3rd Operation: We can pick 1 & 2, subtract 2-1 => {1, 1, 1}
- 4th Operation: We can pick 1 & 1, subtract 1-1 => {1, 0, 1}
- 5th Operation: We can pick 1 & 1, subtract 1-1 => {0, 0, 1}
After this, no operation can be performed, so the maximum no left in the array is 1, so the answer is 1.
Input: n = 2, arr[] = {2, 4}
Output: 2
Explanation:
- 1st Operation : We can pick 4 & 2, subtract 4-2 => {2, 2}
- 2nd Operation : We can pick 2 & 2, subtract 2-2 => {0, 2}
After this, no operation can be performed, so the maximum no left in the array is 2, so the answer is 2.
Approach:
Intuition behind this approach is to use sorting in ascending order to bring the closest elements together. And by iterating over the sorted array, we calculate the difference between adjacent elements to find the minimum difference. then minimum difference between adjacent elements gives the minimum value after performing the operations.
To do this, we can use the following steps:
- Sort the given array in ascending order.
- Initialize the minimum_value variable to the maximum integer value.
- Iterate over the array from the first element to the second-to-last element.
- Calculate the difference between the current element and the next element.
- If the difference is smaller than the minimum_value, update the minimum_value.
- Return the minimum_value as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minimizeArrayValues(vector< int >& array)
{
sort(array.begin(), array.end());
int minimum_value = INT_MAX;
for ( int i = 0; i < array.size() - 1; i++) {
int new_value = array[i + 1] - array[i];
if (new_value < minimum_value) {
minimum_value = new_value;
}
}
return minimum_value;
}
int main()
{
vector< int > array = { 3, 2, 4 };
int minimum_value = minimizeArrayValues(array);
cout << minimum_value << endl;
return 0;
}
|
Java
import java.util.Arrays;
public class GFG {
public static int minimizeArrayValues( int [] array) {
Arrays.sort(array);
int minimumValue = Integer.MAX_VALUE;
for ( int i = 0 ; i < array.length - 1 ; i++) {
int newValue = array[i + 1 ] - array[i];
if (newValue < minimumValue) {
minimumValue = newValue;
}
}
return minimumValue;
}
public static void main(String[] args) {
int [] array = { 3 , 2 , 4 };
int minimumValue = minimizeArrayValues(array);
System.out.println(minimumValue);
}
}
|
Python3
def minimize_array_values(array):
array.sort()
minimum_value = float ( 'inf' )
for i in range ( len (array) - 1 ):
new_value = array[i + 1 ] - array[i]
if new_value < minimum_value:
minimum_value = new_value
return minimum_value
if __name__ = = "__main__" :
array = [ 3 , 2 , 4 ]
minimum_value = minimize_array_values(array)
print (minimum_value)
|
C#
using System;
public class GFG {
public static int MinimizeArrayValues( int [] array)
{
Array.Sort(array);
int minimumValue = int .MaxValue;
for ( int i = 0; i < array.Length - 1; i++) {
int newValue = array[i + 1] - array[i];
if (newValue < minimumValue) {
minimumValue = newValue;
}
}
return minimumValue;
}
public static void Main( string [] args)
{
int [] array = { 3, 2, 4 };
int minimumValue = MinimizeArrayValues(array);
Console.WriteLine(minimumValue);
}
}
|
Javascript
function minimizeArrayValues(array) {
array.sort((a, b) => a - b);
let minimumValue = Infinity;
for (let i = 0; i < array.length - 1; i++) {
let newValue = array[i + 1] - array[i];
if (newValue < minimumValue) {
minimumValue = newValue;
}
}
return minimumValue;
}
const array = [3, 2, 4];
const minimumValue = minimizeArrayValues(array);
console.log(minimumValue);
|
Time Complexity: O(N*logN)
Auxiliary Space: O(1)
Approach: This can be solved with the following idea:
This problem can be solved using Heap Data Structure.
Below are the steps involved in the implementation of the code:
- If the size of the array is 1 then that element is the answer.
- A max-heap is created and all elements of the array are put into the max-heap.
- Now we take the top 2 elements of the heap until the second element is greater than zero.
- We subtract the second element from the first element and push the first element back into the heap.
- Finally, the answer is when the second element becomes the first element.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minimumNumber( int n, vector< int >& arr)
{
if (n == 1)
return arr[0];
priority_queue< int > pq(arr.begin(), arr.end());
while (1) {
int a = pq.top();
pq.pop();
int b = pq.top();
if (b == 0)
return a;
a -= b;
pq.push(a);
}
}
int main()
{
int n = 3;
vector< int > arr = { 3, 2, 4 };
cout << minimumNumber(n, arr);
return 0;
}
|
Java
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Vector;
public class GFG {
public static int minimumNumber( int n,
Vector<Integer> arr)
{
if (n == 1 )
return arr.get( 0 );
PriorityQueue<Integer> pq = new PriorityQueue<>(
Collections.reverseOrder());
pq.addAll(arr);
while ( true ) {
int a = pq.peek();
pq.poll();
int b = pq.peek();
if (b == 0 )
return a;
a -= b;
pq.add(a);
}
}
public static void main(String[] args)
{
int n = 3 ;
Vector<Integer> arr = new Vector<>();
arr.add( 3 );
arr.add( 2 );
arr.add( 4 );
System.out.println(minimumNumber(n, arr));
}
}
|
Python3
import heapq
def minimumNumber(n, arr):
if n = = 1 :
return arr[ 0 ]
pq = []
for num in arr:
heapq.heappush(pq, - num)
while True :
a = - heapq.heappop(pq)
b = - pq[ 0 ]
if b = = 0 :
return a
a - = b
heapq.heappush(pq, - a)
if __name__ = = "__main__" :
n = 3
arr = [ 3 , 2 , 4 ]
print (minimumNumber(n, arr))
|
C#
using System;
using System.Collections.Generic;
public class Program
{
public static int MinimumNumber( int n, List< int > arr)
{
if (n == 1)
return arr[0];
PriorityQueue< int > pq = new PriorityQueue< int >(arr);
while ( true )
{
int a = pq.Peek();
pq.Pop();
int b = pq.Peek();
if (b == 0)
return a;
a -= b;
pq.Push(a);
}
}
public static void Main( string [] args)
{
int n = 3;
List< int > arr = new List< int > { 3, 2, 4 };
Console.WriteLine(MinimumNumber(n, arr));
}
}
public class PriorityQueue<T> where T : IComparable<T>
{
private List<T> heap;
public PriorityQueue()
{
heap = new List<T>();
}
public PriorityQueue(IEnumerable<T> collection)
{
heap = new List<T>(collection);
BuildHeap();
}
public void Push(T item)
{
heap.Add(item);
int i = heap.Count - 1;
while (i > 0 && heap[(i - 1) / 2].CompareTo(heap[i]) < 0)
{
Swap(i, (i - 1) / 2);
i = (i - 1) / 2;
}
}
public T Pop()
{
T root = heap[0];
heap[0] = heap[heap.Count - 1];
heap.RemoveAt(heap.Count - 1);
Heapify(0);
return root;
}
public T Peek()
{
return heap[0];
}
private void BuildHeap()
{
for ( int i = heap.Count / 2 - 1; i >= 0; i--)
{
Heapify(i);
}
}
private void Heapify( int i)
{
int left = 2 * i + 1;
int right = 2 * i + 2;
int largest = i;
if (left < heap.Count && heap[left].CompareTo(heap[largest]) > 0)
{
largest = left;
}
if (right < heap.Count && heap[right].CompareTo(heap[largest]) > 0)
{
largest = right;
}
if (largest != i)
{
Swap(i, largest);
Heapify(largest);
}
}
private void Swap( int i, int j)
{
T temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
}
|
Javascript
function minimumNumber(n, arr) {
if (n === 1) {
return arr[0];
}
let pq = new PriorityQueue();
for (let num of arr) {
pq.enqueue(num);
}
while ( true ) {
let a = pq.dequeue();
let b = pq.peek();
if (b === 0) {
return a;
}
a -= b;
pq.enqueue(a);
}
}
class PriorityQueue {
constructor() {
this .heap = [];
}
enqueue(value) {
this .heap.push(value);
this .bubbleUp( this .heap.length - 1);
}
dequeue() {
if ( this .isEmpty()) {
return null ;
}
this .swap(0, this .heap.length - 1);
const value = this .heap.pop();
this .bubbleDown(0);
return value;
}
peek() {
if ( this .isEmpty()) {
return null ;
}
return this .heap[0];
}
isEmpty() {
return this .heap.length === 0;
}
bubbleUp(index) {
const parentIndex = Math.floor((index - 1) / 2);
if (parentIndex >= 0 && this .heap[parentIndex] < this .heap[index]) {
this .swap(parentIndex, index);
this .bubbleUp(parentIndex);
}
}
bubbleDown(index) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let maxIndex = index;
if (
leftChildIndex < this .heap.length &&
this .heap[leftChildIndex] > this .heap[maxIndex]
) {
maxIndex = leftChildIndex;
}
if (
rightChildIndex < this .heap.length &&
this .heap[rightChildIndex] > this .heap[maxIndex]
) {
maxIndex = rightChildIndex;
}
if (maxIndex !== index) {
this .swap(maxIndex, index);
this .bubbleDown(maxIndex);
}
}
swap(i, j) {
[ this .heap[i], this .heap[j]] = [ this .heap[j], this .heap[i]];
}
}
let n = 3;
let arr = [3, 2, 4];
document.write(minimumNumber(n, arr));
</script>
|
Time Complexity: O(N*logN)
Auxiliary Space: O(N)
Last Updated :
16 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...