The Wayback Machine - https://web.archive.org/web/20241127230907/https://www.geeksforgeeks.org/min-max-range-queries-array/
Open In App

Min-Max Range Queries in Array

Last Updated : 14 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[0 . . . n-1]. We need to efficiently find the minimum and maximum value from index qs (query start) to qe (query end) where 0 <= qs <= qe <= n-1. We are given multiple queries

Examples: 

Input: arr[] = {1, 8, 5, 9, 6, 14, 2, 4, 3, 7}, queries = 5

        qs = 0 qe = 4
        qs = 3 qe = 7
        qs = 1 qe = 6
        qs = 2 qe = 5
        qs = 0 qe = 8

Output: Minimum = 1 and Maximum = 9 
              Minimum = 2 and Maximum = 14 
              Minimum = 2 and Maximum = 14
              Minimum = 5 and Maximum = 14
              Minimum = 1 and Maximum = 14 

Input: arr[] = {2, 5, 3, 1, 8}, queries = 2

        qs = 2 qe = 3
        qs = 0 qe = 2

Output: Minimum = 1 and Maximum = 3 
              Minimum = 2 and Maximum = 5 

Naive Approach: To solve the problem follow the below idea:

We solve this problem using the Tournament Method for each query.
The time complexity of this approach will be O(queries * n)

Min-Max Range Queries in Array using segment trees:

To solve the problem follow the below idea:

This problem can be solved more efficiently by using a Segment Tree

Below is the implementation of the above approach:

C++




// C++ program to find minimum and maximum using segment
// tree
#include <bits/stdc++.h>
using namespace std;
 
// Node for storing minimum and maximum value of given range
struct node {
    int minimum;
    int maximum;
};
 
// A utility function to get the middle index from corner
// indexes.
int getMid(int s, int e) { return s + (e - s) / 2; }
 
/*  A recursive function to get the minimum and maximum
   value in a given range of array indexes. The following
   are parameters for this function.
 
    st    --> Pointer to segment tree
    index --> Index of current node in the segment tree.
   Initially 0 is passed as root is always at index 0 ss &
   se  --> Starting and ending indexes of the segment
                  represented  by current node, i.e.,
   st[index] qs & qe  --> Starting and ending indexes of
   query range */
struct node MaxMinUntill(struct node* st, int ss, int se,
                         int qs, int qe, int index)
{
    // If segment of this node is a part of given range,
    // then return
    //  the minimum and maximum node of the segment
    struct node tmp, left, right;
    if (qs <= ss && qe >= se)
        return st[index];
 
    // If segment of this node is outside the given range
    if (se < qs || ss > qe) {
        tmp.minimum = INT_MAX;
        tmp.maximum = INT_MIN;
        return tmp;
    }
 
    // If a part of this segment overlaps with the given
    // range
    int mid = getMid(ss, se);
    left = MaxMinUntill(st, ss, mid, qs, qe, 2 * index + 1);
    right = MaxMinUntill(st, mid + 1, se, qs, qe,
                         2 * index + 2);
    tmp.minimum = min(left.minimum, right.minimum);
    tmp.maximum = max(left.maximum, right.maximum);
    return tmp;
}
 
// Return minimum and maximum of elements in range from
// index qs (query start) to qe (query end).  It mainly uses
// MaxMinUtill()
struct node MaxMin(struct node* st, int n, int qs, int qe)
{
    struct node tmp;
 
    // Check for erroneous input values
    if (qs < 0 || qe > n - 1 || qs > qe) {
        printf("Invalid Input");
        tmp.minimum = INT_MAX;
        tmp.maximum = INT_MIN;
        return tmp;
    }
 
    return MaxMinUntill(st, 0, n - 1, qs, qe, 0);
}
 
// A recursive function that constructs Segment Tree for
// array[ss..se]. si is index of current node in segment
// tree st
void constructSTUtil(int arr[], int ss, int se,
                     struct node* st, int si)
{
    // If there is one element in array, store it in current
    // node of segment tree and return
    if (ss == se) {
        st[si].minimum = arr[ss];
        st[si].maximum = arr[ss];
        return;
    }
 
    // If there are more than one elements, then recur for
    // left and right subtrees and store the minimum and
    // maximum of two values in this node
    int mid = getMid(ss, se);
    constructSTUtil(arr, ss, mid, st, si * 2 + 1);
    constructSTUtil(arr, mid + 1, se, st, si * 2 + 2);
 
    st[si].minimum = min(st[si * 2 + 1].minimum,
                         st[si * 2 + 2].minimum);
    st[si].maximum = max(st[si * 2 + 1].maximum,
                         st[si * 2 + 2].maximum);
}
 
/* Function to construct segment tree from given array. This
   function allocates memory for segment tree and calls
   constructSTUtil() to fill the allocated memory */
struct node* constructST(int arr[], int n)
{
    // Allocate memory for segment tree
 
    // Height of segment tree
    int x = (int)(ceil(log2(n)));
 
    // Maximum size of segment tree
    int max_size = 2 * (int)pow(2, x) - 1;
 
    struct node* st = new struct node[max_size];
 
    // Fill the allocated memory st
    constructSTUtil(arr, 0, n - 1, st, 0);
 
    // Return the constructed segment tree
    return st;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 8, 5, 9, 6, 14, 2, 4, 3, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Build segment tree from given array
    struct node* st = constructST(arr, n);
 
    int qs = 0; // Starting index of query range
    int qe = 8; // Ending index of query range
    struct node result = MaxMin(st, n, qs, qe);
 
    // Function call
    printf("Minimum = %d and Maximum = %d ", result.minimum,
           result.maximum);
 
    return 0;
}


Java




// Java program to find minimum and maximum using segment
// tree
import java.util.*;
 
public class GFG {
    public static class Node {
        int minimum;
        int maximum;
        Node(int minimum, int maximum)
        {
            this.minimum = minimum;
            this.maximum = maximum;
        }
    }
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 1, 8, 5, 9, 6, 14, 2, 4, 3, 7 };
        int n = arr.length;
        Node[] st = constructST(arr, n);
        int qs = 0; // Starting index of query range
        int qe = 8; // Ending index of query range
        Node result = MaxMin(st, n, qs, qe);
 
        System.out.println("Minimum = " + result.minimum
                           + " and Maximum = "
                           + result.maximum);
    }
    // A utility function to get the middle index from
    // corner
    // indexes.
    public static int getMid(int s, int e)
    {
        return s + (e - s) / 2;
    }
 
    /*  A recursive function to get the minimum and maximum
     value in a given range of array indexes. The following
     are parameters for this function.
 
      st    --> Pointer to segment tree
      index --> Index of current node in the segment tree.
     Initially 0 is passed as root is always at index 0 ss &
     se  --> Starting and ending indexes of the segment
                    represented  by current node, i.e.,
     st[index] qs & qe  --> Starting and ending indexes of
     query range */
    public static Node MaxMinUntill(Node[] st, int ss,
                                    int se, int qs, int qe,
                                    int index)
    {
        // If segment of this node is a part of given range,
        // then return
        //  the minimum and maximum node of the segment
        Node tmp;
        Node left;
        Node right;
        if (qs <= ss && qe >= se)
            return st[index];
        // If segment of this node is outside the given
        // range
        if (se < qs || ss > qe) {
            tmp = new Node(Integer.MAX_VALUE,
                           Integer.MIN_VALUE);
            return tmp;
        }
        // If a part of this segment overlaps with the given
        // range
        int mid = getMid(ss, se);
        left = MaxMinUntill(st, ss, mid, qs, qe,
                            2 * index + 1);
        right = MaxMinUntill(st, mid + 1, se, qs, qe,
                             2 * index + 2);
        tmp = new Node(
            Math.min(left.minimum, right.minimum),
            Math.max(left.maximum, right.maximum));
        return tmp;
    }
 
    // Return minimum and maximum of elements in range from
    // index qs (query start) to qe (query end).  It mainly
    // uses MaxMinUtill()
    public static Node MaxMin(Node[] st, int n, int qs,
                              int qe)
    {
        Node tmp;
        // Check for erroneous input values
        if (qs < 0 || qe > n - 1 || qs > qe) {
            System.out.println("Invalid Input");
            tmp = new Node(Integer.MAX_VALUE,
                           Integer.MIN_VALUE);
            return tmp;
        }
        return MaxMinUntill(st, 0, n - 1, qs, qe, 0);
    }
 
    // A recursive function that constructs Segment Tree for
    // array[ss..se]. si is index of current node in segment
    // tree st
    public static void constructSTUtil(int[] arr, int ss,
                                       int se, Node[] st,
                                       int si)
    {
        // If there is one element in array, store it in
        // current
        // node of segment tree and return
        if (ss == se) {
            st[si] = new Node(arr[ss], arr[ss]);
            return;
        }
 
        // If there are more than one elements, then recur
        // for left and right subtrees and store the minimum
        // and maximum of two values in this node
        int mid = getMid(ss, se);
        constructSTUtil(arr, ss, mid, st, si * 2 + 1);
        constructSTUtil(arr, mid + 1, se, st, si * 2 + 2);
        int min = Math.min(st[si * 2 + 1].minimum,
                           st[si * 2 + 2].minimum);
        int max = Math.max(st[si * 2 + 1].maximum,
                           st[si * 2 + 2].maximum);
        st[si] = new Node(min, max);
    }
 
    /* Function to construct segment tree from given array.
     This function allocates memory for segment tree and
     calls constructSTUtil() to fill the allocated memory */
    public static Node[] constructST(int[] arr, int n)
    {
        // Allocate memory for segment tree
        // Height of segment tree
        int x = (int)(Math.ceil(Math.log(n) / Math.log(2)));
        // Maximum size of segment tree
        int max_size = 2 * (int)(Math.pow(2, x)) - 1;
        Node[] st = new Node[max_size];
        // Fill the allocated memory st
        constructSTUtil(arr, 0, n - 1, st, 0);
        return st;
    }
}


Python3




# python program to find minimum and maximum using segment
# tree
import math
 
# Node for storing minimum and maximum value of given range
class Node:
    def __init__(self):
        self.minimum = math.inf
        self.maximum = -math.inf
 
# A utility function to get the middle index from corner
# indexes.
def getMid(s, e):
    return s + (e - s) // 2
 
 
""" A recursive function to get the minimum and maximum
   value in a given range of array indexes. The following
   are parameters for this function.
 
    st    --> Pointer to segment tree
    index --> Index of current node in the segment tree.
   Initially 0 is passed as root is always at index 0 ss &
   se  --> Starting and ending indexes of the segment
                  represented  by current node, i.e.,
   st[index] qs & qe  --> Starting and ending indexes of
   query range """
 
 
def MaxMinUntill(st, ss, se, qs, qe, index):
    # If segment of this node is a part of given range,
    # then return
    #  the minimum and maximum node of the segment
    tmp = Node()
    if qs <= ss and qe >= se:
        return st[index]
 
    # If segment of this node is outside the given range
    if se < qs or ss > qe:
        return tmp
 
    # If a part of this segment overlaps with the given
    # range
    mid = getMid(ss, se)
    left = MaxMinUntill(st, ss, mid, qs, qe, 2 * index + 1)
    right = MaxMinUntill(st, mid + 1, se, qs, qe, 2 * index + 2)
    tmp.minimum = min(left.minimum, right.minimum)
    tmp.maximum = max(left.maximum, right.maximum)
    return tmp
 
# Return minimum and maximum of elements in range from
# index qs (query start) to qe (query end).  It mainly uses
# MaxMinUtill()
 
 
def MaxMin(st, n, qs, qe):
    tmp = Node()
 
    # Check for erroneous input values
    if qs < 0 or qe > n - 1 or qs > qe:
        print("Invalid Input")
        return tmp
    return MaxMinUntill(st, 0, n - 1, qs, qe, 0)
 
# A recursive function that constructs Segment Tree for
# array[ss..se]. si is index of current node in segment
# tree st
 
 
def constructSTUtil(arr, ss, se, st, si):
    # If there is one element in array, store it in current
    # node of segment tree and return
    if ss == se:
        st[si].minimum = arr[ss]
        st[si].maximum = arr[ss]
        return
 
    # If there are more than one elements, then recur for
    # left and right subtrees and store the minimum and
    # maximum of two values in this node
    mid = getMid(ss, se)
    constructSTUtil(arr, ss, mid, st, si * 2 + 1)
    constructSTUtil(arr, mid + 1, se, st, si * 2 + 2)
    st[si].minimum = min(st[si * 2 + 1].minimum, st[si * 2 + 2].minimum)
    st[si].maximum = max(st[si * 2 + 1].maximum, st[si * 2 + 2].maximum)
 
 
""" Function to construct segment tree from given array. This
   function allocates memory for segment tree and calls
   constructSTUtil() to fill the allocated memory """
 
 
def constructST(arr, n):
    # Allocate memory for segment tree
 
    # Height of segment tree
    x = math.ceil(math.log2(n))
 
    # Maximum size of segment tree
    max_size = 2 * (2 ** x) - 1
    st = [Node() for i in range(max_size)]
 
    # Fill the allocated memory st
    constructSTUtil(arr, 0, n - 1, st, 0)
 
    # Return the constructed segment tree
    return st
 
 
# Driver code
arr = [1, 8, 5, 9, 6, 14, 2, 4, 3, 7]
n = len(arr)
 
# Build segment tree from given array
st = constructST(arr, n)
qs = 0  # Starting index of query range
qe = 8  # Ending index of query range
result = MaxMin(st, n, qs, qe)
 
# Function call
print("Minimum =", result.minimum, "and Maximum =", result.maximum)


C#




//C# program to find minimum and maximum using segment
// tree
using System;
 
public class GFG {
    public class Node {
        public int minimum;
        public int maximum;
        public Node(int minimum, int maximum)
        {
            this.minimum = minimum;
            this.maximum = maximum;
        }
    }
  // A utility function to get the middle index from
    // corner
    // indexes.
    public static int getMid(int s, int e)
    {
        return s + (e - s) / 2;
    }
  /*  A recursive function to get the minimum and maximum
     value in a given range of array indexes. The following
     are parameters for this function.
 
      st    --> Pointer to segment tree
      index --> Index of current node in the segment tree.
     Initially 0 is passed as root is always at index 0 ss &
     se  --> Starting and ending indexes of the segment
                    represented  by current node, i.e.,
     st[index] qs & qe  --> Starting and ending indexes of
     query range */
    public static Node MaxMinUntill(Node[] st, int ss,
                                    int se, int qs, int qe,
                                    int index)
    {
        // If segment of this node is a part of given range,
        // then return
        //  the minimum and maximum node of the segment
        Node tmp;
        Node left;
        Node right;
  
        if (qs <= ss && qe >= se)
            return st[index];
    // If segment of this node is outside the given
        // range
        if (se < qs || ss > qe) {
            tmp = new Node(int.MaxValue, int.MinValue);
            return tmp;
        }
 // If a part of this segment overlaps with the given
        // range
        int mid = getMid(ss, se);
        left = MaxMinUntill(st, ss, mid, qs, qe,
                            2 * index + 1);
        right = MaxMinUntill(st, mid + 1, se, qs, qe,
                             2 * index + 2);
        tmp = new Node(
            Math.Min(left.minimum, right.minimum),
            Math.Max(left.maximum, right.maximum));
        return tmp;
    }
 
    // Return minimum and maximum of elements in range from
    // index qs (query start) to qe (query end).  It mainly
    // uses MaxMinUtill()
    public static Node MaxMin(Node[] st, int n, int qs,
                              int qe)
    {
        Node tmp;
       
        // Check for erroneous input values
        if (qs < 0 || qe > n - 1 || qs > qe) {
            Console.WriteLine("Invalid Input");
            tmp = new Node(int.MaxValue, int.MinValue);
            return tmp;
        }
        return MaxMinUntill(st, 0, n - 1, qs, qe, 0);
    }
   // A recursive function that constructs Segment Tree for
    // array[ss..se]. si is index of current node in segment
    // tree st
    public static void constructSTUtil(int[] arr, int ss,
                                       int se, Node[] st,
                                       int si)
    {
       // If there is one element in array, store it in
        // current
        // node of segment tree and return
        if (ss == se) {
            st[si] = new Node(arr[ss], arr[ss]);
            return;
        }
  // If there are more than one elements, then recur
        // for left and right subtrees and store the minimum
        // and maximum of two values in this node
        int mid = getMid(ss, se);
        constructSTUtil(arr, ss, mid, st, si * 2 + 1);
        constructSTUtil(arr, mid + 1, se, st, si * 2 + 2);
        int min = Math.Min(st[si * 2 + 1].minimum,
                           st[si * 2 + 2].minimum);
        int max = Math.Max(st[si * 2 + 1].maximum,
                           st[si * 2 + 2].maximum);
        st[si] = new Node(min, max);
    }
 /* Function to construct segment tree from given array.
     This function allocates memory for segment tree and
     calls constructSTUtil() to fill the allocated memory */
    public static Node[] constructST(int[] arr, int n)
    {
        // Allocate memory for segment tree
        // Height of segment tree
        int x = (int)(Math.Ceiling(Math.Log(n)
                                   / Math.Log(2)));
       // Maximum size of segment tree
        int max_size = 2 * (int)(Math.Pow(2, x)) - 1;
              // Fill the allocated memory st
        Node[] st = new Node[max_size];
        constructSTUtil(arr, 0, n - 1, st, 0);
        return st;
    }
 // Driver Code
    public static void Main(string[] args)
    {
        int[] arr = { 1, 8, 5, 9, 6, 14, 2, 4, 3, 7 };
        int n = arr.Length;
        Node[] st = constructST(arr, n);
        int qs = 0;
        int qe = 8;
        Node result = MaxMin(st, n, qs, qe);
        Console.WriteLine("Minimum = " + result.minimum
                          + " and Maximum = "
                          + result.maximum);
    }
}


Javascript




// JavaScript program to find minimum and maximum using segment
// tree
 
// A utility function to get the middle index from corner
// indexes.
function getMid(s, e) {
  return Math.floor(s + (e - s) / 2);
}
 
// Node for storing minimum and maximum value of given range
class Node {
  constructor(minimum, maximum) {
    this.minimum = minimum;
    this.maximum = maximum;
  }
}
 
/*  A recursive function to get the minimum and maximum
   value in a given range of array indexes. The following
   are parameters for this function.
  
    st    --> Pointer to segment tree
    index --> Index of current node in the segment tree.
   Initially 0 is passed as root is always at index 0 ss &
   se  --> Starting and ending indexes of the segment
                  represented  by current node, i.e.,
   st[index] qs & qe  --> Starting and ending indexes of
   query range */
function MaxMinUntill(st, ss, se, qs, qe, index) {
     
    // If segment of this node is a part of given range,
    // then return
    //  the minimum and maximum node of the segment
    let tmp, left, right;
    if (qs <= ss && qe >= se) {
        return st[index];
    }
     
    // If segment of this node is outside the given range
    if (se < qs || ss > qe) {
        tmp = new Node(Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER);
        return tmp;
    }
     
    // If a part of this segment overlaps with the given
    // range
    const mid = getMid(ss, se);
    left = MaxMinUntill(st, ss, mid, qs, qe, 2 * index + 1);
    right = MaxMinUntill(st, mid + 1, se, qs, qe, 2 * index + 2);
    tmp = new Node(Math.min(left.minimum, right.minimum), Math.max(left.maximum, right.maximum));
    return tmp;
}
 
// Return minimum and maximum of elements in range from
// index qs (query start) to qe (query end).  It mainly uses
// MaxMinUtill()
function MaxMin(st, n, qs, qe) {
    let tmp;
     
    // Check for erroneous input values
    if (qs < 0 || qe > n - 1 || qs > qe) {
        console.log("Invalid Input");
        tmp = new Node(Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER);
        return tmp;
    }
     
    return MaxMinUntill(st, 0, n - 1, qs, qe, 0);
}
 
// A recursive function that constructs Segment Tree for
// array[ss..se]. si is index of current node in segment
// tree st
function constructSTUtil(arr, ss, se, st, si) {
   
    // If there is one element in array, store it in current
    // node of segment tree and return
    if (ss == se) {
        st[si] = new Node(arr[ss], arr[ss]);
        return;
    }
     
    // If there are more than one elements, then recur for
    // left and right subtrees and store the minimum and
    // maximum of two values in this node
    var mid = getMid(ss, se);
    constructSTUtil(arr, ss, mid, st, si * 2 + 1);
    constructSTUtil(arr, mid + 1, se, st, si * 2 + 2);
 
    st[si] = new Node(Math.min(st[si * 2 + 1].minimum, st[si * 2 + 2].minimum), Math.max(st[si * 2 + 1].maximum, st[si * 2 + 2].maximum));
}
 
/* Function to construct segment tree from given array. This
   function allocates memory for segment tree and calls
   constructSTUtil() to fill the allocated memory */
function constructST(arr, n) {
     
    // Allocate memory for segment tree
  
    // Height of segment tree
    const x = Math.ceil(Math.log2(n));
     
    // Maximum size of segment tree
    var max_size = 2 * Math.pow(2, x) - 1;
     
    var st = new Array(max_size).fill(null);
     
    // Fill the allocated memory st
    constructSTUtil(arr, 0, n - 1, st, 0);
     
    // Return the constructed segment tree
    return st;
}
 
// Driver code
var arr = [1, 8, 5, 9, 6, 14, 2, 4, 3, 7];
var n = arr.length;
 
// Build segment tree from given array
var st = constructST(arr, n);
var qs = 0; // Starting index of query range
var qe = 8; // Ending index of query range
var result = MaxMin(st, n, qs, qe);
 
// Function call
console.log(`Minimum = ${result.minimum} and Maximum = ${result.maximum}`);
 
// This code is contributed by prasad264


Output

Minimum = 1 and Maximum = 14 

Time Complexity: O(queries * log N)
Auxiliary Space: O(N)

Can we do better if there are no updates on the array? 

The above segment tree-based solution also allows array updates also to happen in O(Log n) time. Assume a situation when there are no updates (or the array is static). We can actually process all queries in O(1) time with some preprocessing. One simple solution is to make a 2D table of nodes that stores all ranges minimum and maximum. This solution requires O(1) query time but requires O(N2) preprocessing time and O(N2) extra space which can be a problem for large N. We can solve this problem in O(1) query time, O(n Log n) space and O(n Log n) preprocessing time using the Sparse Table.

This article is reviewed by team GeeksForGeeks. 

 



Previous Article
Next Article

Similar Reads

Find min and max values among all maximum leaf nodes from all possible Binary Max Heap
Given a positive integer N, the task is to find the largest and smallest elements, from the maximum leaf nodes of every possible binary max-heap formed by taking the first N natural numbers as the nodes' value of the binary max-heap. Examples: Input: N = 2Output: 1 1Explanation: There is only one maximum binary heap with the nodes {1, 2}: In the ab
7 min read
Array range queries over range queries
Given an array of size n and a give set of commands of size m. The commands are enumerated from 1 to m. These commands can be of the following two types of commands: Type 1 [l r (1 <= l <= r <= n)] : Increase all elements of the array by one, whose indices belongs to the range [l, r]. In these queries of the index is inclusive in the range
15+ min read
Count of subsequences with a sum in range [L, R] and difference between max and min element at least X
Given an array arr[] consisting of N positive integers and 3 integers L, R, and X, the task is to find the number of subsequences of size atleast 2 with a sum in the range [L, R], and the difference between the maximum and minimum element is at least X. (N≤15) Examples: Input: arr[] = {1 2 3}, L = 5, R = 6, X = 1Output: 2Explanation: There are two
9 min read
Check presence of integer between min and max of Array that divide all Array elements
Given an array A[] of size N, the task is to check if there exists any integer that divide all the elements of that array and lies in the range of minimum and maximum elements (both included) of that array. Examples: Input: A = {27, 6, 9, 3, 21}Output: 1Explanation: Here, 3 lies between min(3) and max(27) of this array, and divides all elements of
5 min read
Remove minimum elements from array so that max <= 2 * min
Given an array arr, the task is to remove minimum number of elements such that after their removal, max(arr) <= 2 * min(arr). Examples: Input: arr[] = {4, 5, 3, 8, 3} Output: 1 Remove 8 from the array. Input: arr[] = {1, 2, 3, 4} Output: 1 Remove 1 from the array. Approach: Let us fix each value as the minimum value say x and find number of term
6 min read
Remove exactly one element from the array such that max - min is minimum
Given an array consisting of N positive integer numbers. The task is to remove exactly one element from this array to minimize max(a) - min(a) and print the minimum possible (max(a) - min(a)). Note: max(a) means largest number in array [Tex]a [/Tex]and min(a) means smallest number in array [Tex]a [/Tex]. There are at least 2 elements in the array.
8 min read
Count number of Subsequences in Array in which X and Y are min and max elements
Given an array arr[] consisting of N unique elements, the task is to return the count of the subsequences in an array in which the minimum element is X and the maximum element is Y. Examples: Input: arr[] = {2, 4, 6, 7, 5}, X = 2, Y = 5Output: 2Explanation: Subsequences in which the minimum element is X and the maximum element is Y are {2, 5}, {2,
11 min read
Remove minimum elements from the array such that 2*min becomes more than max
Given an array of size N. The task is to remove minimum elements from the array such that twice of minimum number is greater than the maximum number in the modified array. Print the minimum number of elements removed.Examples: Input: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 Remove 4 elements (4, 5, 100, 200) so that 2*min becomes more
6 min read
Divide a sorted array in K parts with sum of difference of max and min minimized in each part
Given an ascending sorted array arr[] of size N and an integer K, the task is to partition the given array into K non-empty subarrays such that the sum of differences of the maximum and the minimum of each subarray is minimized. Examples: Input: arr[] = {4, 8, 15, 16, 23, 42}, K = 3 Output: 12 Explanation: The given array can be split into three su
7 min read
Maximize sum of max and min of each of K Arrays obtained by dividing given Array into given sizes
Given two arrays, arr[] of N size and div[] of size K. Divide arr[] into K different arrays, each of div[i] size. The task is to find the total sum after maximizing the sum of maximum and minimum of each divided array. Examples: Input: arr[] = {3, 1, 7, 4}, div[] = {1, 3}, N = 4, K = 2Output: 19Explanation: Divide the array in the following way: {7
9 min read
Minimize removals in given Array to make max less than twice of min
Given an integer array arr[]. The task is to minimize the number of removals required such that the maximum element in arr[] becomes less than twice the minimum. Examples Input: arr[] = {4, 6, 21, 7, 5, 9, 12}Output: The minimum number of removal operations is 4.Explanation: The newly trimmed array is [7, 5, 9] where 9 is max and 5 is min; 9 < 2
9 min read
Divide a sorted array in K parts with sum of difference of max and min minimized in each part - Set 2
Given an ascending sorted array arr[] of size N and an integer K, the task is to partition the given array into K non-empty subarrays such that the sum of differences of the maximum and the minimum of each subarray is minimized. Examples: Input: arr[] = { 10, 20, 70, 80 }, N = 4, K = 2Output: 20Explanation: The given array can be split in the follo
11 min read
Rank of remaining numbers in Array by replacing first and last with max and min alternatively
Given an array arr[ ] of size N, the task is to find the rank of the remaining element in an array after performing the given operation: In each operation choose elements from both ends and delete them and insert the max of those values at the position of the left element and move one step towards the center from both ends and keep performing this
8 min read
Generate N sized Array with mean K and minimum difference between min and max
Given two integers N and X, the task is to find an output array arr[] containing distinct integers of length N such that their average is K and the difference between the minimum and the maximum is minimum possible. Input: N = 4, X = 8Output :- 6 7 9 10Explanation: Clearly the mean of 6, 7, 9, 10 is 8 and The difference between the max and the min
6 min read
Number of pairs of Array where the max and min of pair is same as their indices
Given an array A[] of N integers, the task is to calculate the total number of pairs of indices (i, j) satisfying the following conditions - 1 ? i < j ? Nminimum(A[i], A[j]) = imaximum(A[i], A[j]) = j Note: 1-based indexing is considered. Examples: Input: N = 4, A[] = {1, 3, 2, 4}Output: 2Explanation: First pair of indices is (1, 4), As minimum(
6 min read
Split array into K Subarrays to minimize sum of difference between min and max
Given a sorted array arr[] of size N and integer K, the task is to split the array into K non-empty subarrays such that the sum of the difference between the maximum element and the minimum element of each subarray is minimized. Note: Every element of the array must be included in one subarray and each subarray should be non-empty. Examples: Input:
6 min read
Count ways to split Array such that sum of max of left and min of right is at least K
Given an array A[] consisting of N integers and an integer K. The task is to find the total number of ways in which you can divide the array into two parts such that the sum of the largest element in the left part and the smallest element in the right part is greater than or equal to K. Examples: Input: A[] = {1, 2, 3}, N = 3, K = 3Output: 2Explana
6 min read
Find largest positive integer x missing from unsorted array such that min(arr[]) < x < max(arr[])
Given an array arr[] containing integers. The task is to find the largest positive integer x missing from the array such that min(arr[]) < x < max(arr[]). Examples Input: arr[] = {2, 3, 7, 6, 8}Output: 5Explanation: 5 is the largest positive integer missing from arr[] and 2 < 5 < 8. Input: arr[] = { 2, 3, -7, 1, 4 }Output: -1 Naive Appr
9 min read
Minimum removals from array to make max - min <= K
Given N integers and K, find the minimum number of elements that should be removed, such that Amax-Amin<=K. After the removal of elements, Amax and Amin is considered among the remaining elements. Examples: Input : a[] = {1, 3, 4, 9, 10, 11, 12, 17, 20}, k = 4 Output : 5 Explanation: Remove 1, 3, 4 from beginning and 17, 20 from the end. Input :
15+ min read
Convert Min Heap to Max Heap
Given an array representation of min Heap, convert it to max Heap. Examples: Input: arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9} 3 / \ 5 9 / \ / \ 6 8 20 10 / \ /12 18 9 Output: arr[] = {20, 18, 10, 12, 9, 9, 3, 5, 6, 8} 20 / \ 18 10 / \ / \ 12 9 9 3 / \ /5 6 8 Input: arr[] = {3, 4, 8, 11, 13}Output: arr[] = {13, 11, 8, 4, 3} Approach: To solve the p
10 min read
Minimize (max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) of three different sorted arrays
Given three sorted arrays A, B, and C of not necessarily same sizes. Calculate the minimum absolute difference between the maximum and minimum number of any triplet A[i], B[j], C[k] such that they belong to arrays A, B and C respectively, i.e., minimize (max(A[i], B[j], C[k]) - min(A[i], B[j], C[k])) Examples: Input : A : [ 1, 4, 5, 8, 10 ] B : [ 6
8 min read
Minimum value of "max + min" in a subarray
Given a array of n positive elements we need to find the lowest possible sum of max and min elements in a subarray given that size of subarray should be greater than equal to 2. Examples: Input : arr[] = {1 12 2 2} Output : 4 Sum of 2+2 of subarray [2, 2] Input : arr[] = {10 20 30 40 23 45} Output : 30 Sum of 10+20 of subarray[10, 20] A simple solu
4 min read
Longest subarray such that the difference of max and min is at-most one
Given an array of n numbers where the difference between each number and the previous one doesn't exceed one. Find the longest contiguous subarray such that the difference between the maximum and minimum number in the range doesn't exceed one. Examples: Input : {3, 3, 4, 4, 5, 6} Output : 4 The longest subarray here is {3, 3, 4, 4} Input : {7, 7, 7
7 min read
Find the value of max(f(x)) - min(f(x)) for a given F(x)
Given two sequences of N integers consisting of both positive and negative integers, inclusive of 0 (sequence A and sequence B). Then there will be Q queries. In each, you will be given two integers l and r (r>=l). Let's define a function: [Tex] \large f(x, y)=\sum_{i=l}^r(A_i*x-B_i*y) [/Tex] The task is to print the value of Max(f(x, y)) - Min(
10 min read
Min and Max in a List in Java
Given an unsorted list of integers, find maximum and minimum values in it. Input : list = [10, 4, 3, 2, 1, 20] Output : max = 20, min = 1 Input : list = [10, 400, 3, 2, 1, -1] Output : max = 400, min = -1Sorting This is least efficient approach but will get the work done. The idea is to sort the list in natural order, then the first or last element
5 min read
Sum of width (max and min diff) of all Subsequences
Given an array A[] of integers. The task is to return the sum of the width of all subsequences of A. For any sequence S, the width of S is the difference between the maximum and minimum elements of S. Note: Since the answer can be large, print the answer modulo 10^9 + 7. Examples: Input : A[] = {1, 3, 2} Output : 6 Subsequences are {1}, {2}, {3}, {
5 min read
Partition N into M parts such that difference between Max and Min part is smallest
Given two integers N and M, partition N into M integers such that the difference between the maximum and minimum integer obtained by the partition is as small as possible. Print the M numbers A1, A2....Am, such that: sum(A) = N.max(A)-min(A) is minimized. Examples: Input : N = 11, M = 3 Output : A[] = {4, 4, 3} Input : N = 8, M = 4 Output : A[] = {
5 min read
Print Binary Search Tree in Min Max Fashion
Given a Binary Search Tree (BST), the task is to print the BST in min-max fashion. What is min-max fashion? A min-max fashion means you have to print the maximum node first then the minimum then the second maximum then the second minimum and so on. Examples: Input: 100 / \ 20 500 / \ 10 30 \ 40 Output: 10 500 20 100 30 40 Input: 40 / \ 20 50 / \ \
10 min read
Min-Max Product Tree of a given Binary Tree
Given a Binary Tree, the task is to convert the given Binary tree into Min-Max Product Tree and print the level-order sequence of the modified tree. Min-Max Product Tree: A Min-Max Product Tree contains the product of the minimum and maximum values of its left and right subtrees at each node. Note: For any node having only a single child, the value
14 min read
Min and max length subarray having adjacent element difference atmost K
Given an array arr[] and an integer K, the task is to find the maximum and minimum length subarray such that the difference between adjacent elements is at most K.Examples: Input: arr[] = {2, 4, 6}, K = 2 Output: 3, 3 Explanation: Minimum and Maximum length subarray such that difference between adjacent elements is at most is 3, which is {2, 4, 2}I
9 min read
three90RightbarBannerImg