Open In App

Find the minimised number using given operations

Improve
Improve
Like Article
Like
Save
Share
Report

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 the array in ascending order.
    sort(array.begin(), array.end());
 
    // Initialize the minimum value to the maximum value in
    // the array.
    int minimum_value = INT_MAX;
 
    // Iterate over all pairs of elements in the array.
    for (int i = 0; i < array.size() - 1; i++) {
        // Subtract the adjacent elements.
        int new_value = array[i + 1] - array[i];
 
        // If the new value is less than the minimum value,
        // update the minimum value.
        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




//Java program for the above approach
import java.util.Arrays;
 
public class GFG {
 
    public static int minimizeArrayValues(int[] array) {
        // Sort the array in ascending order.
        Arrays.sort(array);
 
        // Initialize the minimum value to the maximum value in the array.
        int minimumValue = Integer.MAX_VALUE;
 
        // Iterate over all pairs of elements in the array.
        for (int i = 0; i < array.length - 1; i++) {
            // Subtract the adjacent elements.
            int newValue = array[i + 1] - array[i];
 
            // If the new value is less than the minimum value,
            // update the minimum value.
            if (newValue < minimumValue) {
                minimumValue = newValue;
            }
        }
 
        return minimumValue;
    }
 
    // driver code
    public static void main(String[] args) {
        int[] array = {3, 2, 4};
        int minimumValue = minimizeArrayValues(array);
        System.out.println(minimumValue);
    }
}


Python3




#Python3 program for the above approach
def minimize_array_values(array):
    # Sort the array in ascending order.
    array.sort()
 
    # Initialize the minimum value to the maximum value in the array.
    minimum_value = float('inf')
 
    # Iterate over all pairs of elements in the array.
    for i in range(len(array) - 1):
        # Subtract the adjacent elements.
        new_value = array[i + 1] - array[i]
 
        # If the new value is less than the minimum value,
        # update the minimum value.
        if new_value < minimum_value:
            minimum_value = new_value
 
    return minimum_value
 
#driver code
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)
    {
        // Sort the array in ascending order.
        Array.Sort(array);
 
        // Initialize the minimum value to the maximum value
        // in the array.
        int minimumValue = int.MaxValue;
 
        // Iterate over all pairs of elements in the array.
        for (int i = 0; i < array.Length - 1; i++) {
            // Subtract the adjacent elements.
            int newValue = array[i + 1] - array[i];
 
            // If the new value is less than the minimum
            // value, update the minimum value.
            if (newValue < minimumValue) {
                minimumValue = newValue;
            }
        }
 
        return minimumValue;
    }
 
    // driver code
    public static void Main(string[] args)
    {
        int[] array = { 3, 2, 4 };
        int minimumValue = MinimizeArrayValues(array);
        Console.WriteLine(minimumValue);
    }
}


Javascript




function minimizeArrayValues(array) {
    // Sort the array in ascending order.
    array.sort((a, b) => a - b);
 
    // Initialize the minimum value to the maximum value in the array.
    let minimumValue = Infinity;
 
    // Iterate over all pairs of elements in the array.
    for (let i = 0; i < array.length - 1; i++) {
        // Subtract the adjacent elements.
        let newValue = array[i + 1] - array[i];
 
        // If the new value is less than the minimum value, update the minimum value.
        if (newValue < minimumValue) {
            minimumValue = newValue;
        }
    }
 
    return minimumValue;
}
 
const array = [3, 2, 4];
const minimumValue = minimizeArrayValues(array);
console.log(minimumValue);


Output

1
















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++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum Number
int minimumNumber(int n, vector<int>& arr)
{
    if (n == 1)
        return arr[0];
 
    // Itialise priority queue
    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);
    }
}
 
// Driver code
int main()
{
 
    int n = 3;
    vector<int> arr = { 3, 2, 4 };
 
    // Function call
    cout << minimumNumber(n, arr);
    return 0;
}


Java




// Java code for the above approach
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Vector;
 
public class GFG {
    // Function to find the minimum number
    public static int minimumNumber(int n,
                                    Vector<Integer> arr)
    {
        if (n == 1)
            return arr.get(0);
 
        // Initialize a priority queue
        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);
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 3;
        Vector<Integer> arr = new Vector<>();
        arr.add(3);
        arr.add(2);
        arr.add(4);
 
        // Function call
        System.out.println(minimumNumber(n, arr));
    }
}
 
// This code is contributed by Susobhan Akhuli


Python3




# Python code for the above approach
import heapq
 
# Function to find minimum number
def minimumNumber(n, arr):
    if n == 1:
        return arr[0]
 
    # Initialize priority queue
    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)
 
# Driver code
if __name__ == "__main__":
    n = 3
    arr = [3, 2, 4]
 
    # Function call
    print(minimumNumber(n, arr))
 
# This code is contributed by Susobhan Akhuli


C#




using System;
using System.Collections.Generic;
 
public class Program
{
      // Function to find minimum Number
    public static int MinimumNumber(int n, List<int> arr)
    {
        if (n == 1)
            return arr[0];
        // Initialize priority queue
        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 };
        // Function call
        Console.WriteLine(MinimumNumber(n, arr));
    }
}
 
public class PriorityQueue<T> where T : IComparable<T>
{
    private List<T> heap;
 
    public PriorityQueue()
    {
        heap = new List<T>();
    }
 
      // Function to build heap
    public PriorityQueue(IEnumerable<T> collection)
    {
        heap = new List<T>(collection);
        BuildHeap();
    }
 
      // Function to push node in heap
    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;
        }
    }
 
      // Function to pop element from head
    public T Pop()
    {
        T root = heap[0];
        heap[0] = heap[heap.Count - 1];
        heap.RemoveAt(heap.Count - 1);
        Heapify(0);
        return root;
    }
 
      // Function to get peed from headp
    public T Peek()
    {
        return heap[0];
    }
 
      // Function to build head
    private void BuildHeap()
    {
        for (int i = heap.Count / 2 - 1; i >= 0; i--)
        {
            Heapify(i);
        }
    }
     
      // Function to Heapify the heap properly
    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);
        }
    }
      
      // Function to swap element in node.
    private void Swap(int i, int j)
    {
        T temp = heap[i];
        heap[i] = heap[j];
        heap[j] = temp;
    }
}


Javascript




// JavaScript code for the above approach
 
// Function to find the minimum Number
function minimumNumber(n, arr) {
  if (n === 1) { // If there is only one element in the array
    return arr[0]; // Return that element as the minimum
  }
 
  // Initialize a priority queue
  let pq = new PriorityQueue();
  for (let num of arr) {
    pq.enqueue(num); // Add all elements of the array to the priority queue
  }
 
  while (true) {
    let a = pq.dequeue(); // Get the largest element from the priority queue
    let b = pq.peek(); // Get the second largest element from the priority queue
 
    if (b === 0) { // If the second largest element is 0
      return a; // Return the largest element as the minimum
    }
 
    a -= b; // Subtract the second largest element from the largest element
    pq.enqueue(a); // Add the result back to the priority queue
  }
}
 
// Priority Queue class implementation
class PriorityQueue {
  constructor() {
    this.heap = []; // Array to store the elements of the priority queue
  }
 
  enqueue(value) {
    this.heap.push(value); // Add the value to the end of the array
    this.bubbleUp(this.heap.length - 1); // Restore the heap property by bubbling up the value
  }
 
  dequeue() {
    if (this.isEmpty()) {
      return null; // If the priority queue is empty, return null
    }
 
    this.swap(0, this.heap.length - 1); // Swap the first and last elements of the array
    const value = this.heap.pop(); // Remove the last element (previously the first) from the array
    this.bubbleDown(0); // Restore the heap property by bubbling down the new first element
    return value; // Return the removed element
  }
 
  peek() {
    if (this.isEmpty()) {
      return null; // If the priority queue is empty, return null
    }
 
    return this.heap[0]; // Return the first element of the array (highest priority)
  }
 
  isEmpty() {
    return this.heap.length === 0; // Check if the priority queue is empty
  }
 
  bubbleUp(index) {
    const parentIndex = Math.floor((index - 1) / 2); // Calculate the parent index of the
                                                     // current index
 
    if (parentIndex >= 0 && this.heap[parentIndex] < this.heap[index]) { // If the parent is smaller
                                                                         //than the current value
      this.swap(parentIndex, index); // Swap the parent and current values
      this.bubbleUp(parentIndex); // Recursively bubble up the current value
    }
  }
 
  bubbleDown(index) {
    const leftChildIndex = 2 * index + 1; // Calculate the left child index of the current index
    const rightChildIndex = 2 * index + 2; // Calculate the right child index of the current index
    let maxIndex = index; // Assume the current index has the largest value
 
    if (
      leftChildIndex < this.heap.length &&
      this.heap[leftChildIndex] > this.heap[maxIndex]
    ) {
      maxIndex = leftChildIndex; // If the left child is larger, update the max index
    }
 
    if (
      rightChildIndex < this.heap.length &&
      this.heap[rightChildIndex] > this.heap[maxIndex]
    ) {
      maxIndex = rightChildIndex; // If the right child is larger, update the max index
    }
 
    if (maxIndex !== index) {
      this.swap(maxIndex, index); // Swap the current value with the larger child value
      this.bubbleDown(maxIndex); // Recursively bubble down the current value
    }
  }
 
  swap(i, j) {
    [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; // Swap the values at the given
                                                                 // indices
  }
}
 
let n = 3;
let arr = [3, 2, 4];
 
// Function call
document.write(minimumNumber(n, arr));
 
// This code is contributed by Susobhan Akhuli
</script>


Output

1
















Time Complexity: O(N*logN)
Auxiliary Space: O(N)



Last Updated : 16 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads