The Wayback Machine - https://web.archive.org/web/20241129133754/https://www.geeksforgeeks.org/minimum-possible-value-ai-aj-k-given-array-k/
Open In App

Minimum Possible value of |ai + aj – k| for given array and k.

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

You are given an array of n integer and an integer K. Find the number of total unordered pairs {i, j} such that absolute value of (ai + aj – K), i.e., |ai + aj – k| is minimal possible, where i != j.
Examples:  

Input: arr[] = {0, 4, 6, 2, 4},  K = 7
Output: Minimal Value = 1, Total  Pairs = 5 
Explanation: Pairs resulting minimal value are : {a1, a3}, {a2, a4}, {a2, a5}, {a3, a4}, {a4, a5} 
Input: arr[] = {4, 6, 2, 4}  , K = 9
Output: Minimal Value = 1, Total Pairs = 4 
Explanation: Pairs resulting minimal value are : {a1, a2}, {a1, a4}, {a2, a3}, {a2, a4} 

 

A simple solution is iterate over all possible pairs and for each pair we will check whether the value of (ai + aj – K) is smaller than our current smallest value of not. So as per result of above condition we have total of three cases : 
 

  1. abs( ai + aj – K) > smallest : do nothing as this pair will not count in minimal possible value.
  2. abs(ai + aj – K) = smallest : increment the count of pair resulting minimal possible value.
  3. abs( ai + aj – K) < smallest : update the smallest value and set count to 1.

Below is the implementation of the above approach: 

C++




// CPP program to find number of pairs  and minimal
// possible value
#include <bits/stdc++.h>
using namespace std;
  
// function for finding pairs and min value
void pairs(int arr[], int n, int k)
{
    // initialize smallest and count
    int smallest = INT_MAX;
    int count = 0;
  
    // iterate over all pairs
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++) {
            // is abs value is smaller than smallest
            // update smallest and reset count to 1
            if (abs(arr[i] + arr[j] - k) < smallest) {
                smallest = abs(arr[i] + arr[j] - k);
                count = 1;
            }
  
            // if abs value is equal to smallest
            // increment count value
            else if (abs(arr[i] + arr[j] - k) == smallest)
                count++;
        }
  
    // print result
    cout << "Minimal Value = " << smallest << "\n";
    cout << "Total Pairs = " << count << "\n";
}
  
// driver program
int main()
{
    int arr[] = { 3, 5, 7, 5, 1, 9, 9 };
    int k = 12;
    int n = sizeof(arr) / sizeof(arr[0]);
    pairs(arr, n, k);
    return 0;
}


Java




// Java program to find number of pairs
// and minimal possible value
import java.util.*;
  
class GFG {
  
    // function for finding pairs and min value
    static void pairs(int arr[], int n, int k)
    {
        // initialize smallest and count
        int smallest = Integer.MAX_VALUE;
        int count = 0;
  
        // iterate over all pairs
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++) {
                // is abs value is smaller than
                // smallest update smallest and
                // reset count to 1
                if (Math.abs(arr[i] + arr[j] - k)
                    < smallest) {
                    smallest
                        = Math.abs(arr[i] + arr[j] - k);
                    count = 1;
                }
  
                // if abs value is equal to smallest
                // increment count value
                else if (Math.abs(arr[i] + arr[j] - k)
                         == smallest)
                    count++;
            }
  
        // print result
        System.out.println("Minimal Value = " + smallest);
        System.out.println("Total Pairs = " + count);
    }
  
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = { 3, 5, 7, 5, 1, 9, 9 };
        int k = 12;
        int n = arr.length;
        pairs(arr, n, k);
    }
}
// This code is contributed by Arnav Kr. Mandal.


Python3




# Python3 program to find number of pairs
# and minimal possible value
  
# function for finding pairs and min value
  
  
def pairs(arr, n, k):
  
    # initialize smallest and count
    smallest = 999999999999
    count = 0
  
    # iterate over all pairs
    for i in range(n):
        for j in range(i + 1, n):
  
            # is abs value is smaller than smallest
            # update smallest and reset count to 1
            if abs(arr[i] + arr[j] - k) < smallest:
                smallest = abs(arr[i] + arr[j] - k)
                count = 1
  
            # if abs value is equal to smallest
            # increment count value
            elif abs(arr[i] + arr[j] - k) == smallest:
                count += 1
  
    # print result
    print("Minimal Value = ", smallest)
    print("Total Pairs = ", count)
  
  
# Driver Code
if __name__ == '__main__':
    arr = [3, 5, 7, 5, 1, 9, 9]
    k = 12
    n = len(arr)
    pairs(arr, n, k)
  
# This code is contributed by PranchalK


C#




// C# program to find number
// of pairs and minimal
// possible value
using System;
  
class GFG {
  
    // function for finding
    // pairs and min value
    static void pairs(int[] arr, int n, int k)
    {
        // initialize
        // smallest and count
        int smallest = 0;
        int count = 0;
  
        // iterate over all pairs
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++) {
                // is abs value is smaller
                // than smallest update
                // smallest and reset
                // count to 1
                if (Math.Abs(arr[i] + arr[j] - k)
                    < smallest) {
                    smallest
                        = Math.Abs(arr[i] + arr[j] - k);
                    count = 1;
                }
  
                // if abs value is equal
                // to smallest increment
                // count value
                else if (Math.Abs(arr[i] + arr[j] - k)
                         == smallest)
                    count++;
            }
  
        // print result
        Console.WriteLine("Minimal Value = " + smallest);
        Console.WriteLine("Total Pairs = " + count);
    }
  
    // Driver Code
    public static void Main()
    {
        int[] arr = { 3, 5, 7, 5, 1, 9, 9 };
        int k = 12;
        int n = arr.Length;
        pairs(arr, n, k);
    }
}
  
// This code is contributed
// by anuj_67.


PHP




<?php
// PHP program to find number of
// pairs and minimal possible value
  
// function for finding pairs
// and min value
function pairs($arr, $n, $k)
{
      
    // initialize smallest and count
    $smallest = PHP_INT_MAX;
    $count = 0;
  
    // iterate over all pairs
    for ($i = 0; $i < $n; $i++)
        for($j = $i + 1; $j < $n; $j++)
        {
              
            // is abs value is smaller than smallest
            // update smallest and reset count to 1
            if ( abs($arr[$i] + $arr[$j] - $k) < $smallest )
            { 
                $smallest = abs($arr[$i] + $arr[$j] - $k);
                $count = 1;
            }
  
            // if abs value is equal to smallest
            // increment count value
            else if (abs($arr[$i] + 
                     $arr[$j] - $k) == $smallest)
                $count++;
        }
  
        // print result
        echo "Minimal Value = " , $smallest , "\n";
        echo "Total Pairs = ", $count , "\n"; 
} 
  
    // Driver Code
    $arr = array (3, 5, 7, 5, 1, 9, 9);
    $k = 12;
    $n = sizeof($arr);
    pairs($arr, $n, $k);
  
// This code is contributed by aj_36 
?>


Javascript




<script>
  
// Javascript program to find number of pairs  and minimal 
// possible value
  
// function for finding pairs and min value
function pairs(arr, n, k)
{
    // initialize smallest and count
    var smallest = 1000000000;
    var count=0;
  
    // iterate over all pairs
    for (var i=0; i<n; i++)
        for(var j=i+1; j<n; j++)
        {
            // is Math.abs value is smaller than smallest
            // update smallest and reset count to 1
            if ( Math.abs(arr[i] + arr[j] - k) < smallest )
            { 
                smallest = Math.abs(arr[i] + arr[j] - k);
                count = 1;
            }
  
            // if Math.abs value is equal to smallest
            // increment count value
            else if (Math.abs(arr[i] + arr[j] - k) == smallest)
                count++;
        }
  
        // print result
        document.write( "Minimal Value = " + smallest + "<br>");
        document.write( "Total Pairs = " + count + "<br>");    
} 
  
// driver program
var arr = [3, 5, 7, 5, 1, 9, 9];
var k = 12;
var n = arr.length;
pairs(arr, n, k);
  
</script>


Output

Minimal Value = 0
Total Pairs = 4

Time Complexity: O(n2) where n is the number of elements in the array.
Auxiliary Space : O(1)

An efficient solution is to use a self balancing binary search tree (which is implemented in set in C++ and TreeSet in Java). We can find closest element in O(log n) time in map.
 

C++




// C++ program to find number of pairs
// and minimal possible value
#include <bits/stdc++.h>
using namespace std;
  
// function for finding pairs and min value
void pairs(int arr[], int n, int k)
{
    // initialize smallest and count
    int smallest = INT_MAX, count = 0;
    set<int> s;
  
    // iterate over all pairs
    s.insert(arr[0]);
    for (int i = 1; i < n; i++) {
        // Find the closest elements to  k - arr[i]
        int lower
            = *lower_bound(s.begin(), s.end(), k - arr[i]);
  
        int upper
            = *upper_bound(s.begin(), s.end(), k - arr[i]);
  
        // Find absolute value of the pairs formed
        // with closest greater and smaller elements.
        int curr_min = min(abs(lower + arr[i] - k),
                           abs(upper + arr[i] - k));
  
        // is abs value is smaller than smallest
        // update smallest and reset count to 1
        if (curr_min < smallest) {
            smallest = curr_min;
            count = 1;
        }
  
        // if abs value is equal to smallest
        // increment count value
        else if (curr_min == smallest)
            count++;
        s.insert(arr[i]);
  
    } // print result
  
    cout << "Minimal Value = " << smallest << "\n";
    cout << "Total Pairs = " << count << "\n";
}
  
// driver program
int main()
{
    int arr[] = { 3, 5, 7, 5, 1, 9, 9 };
    int k = 12;
    int n = sizeof(arr) / sizeof(arr[0]);
    pairs(arr, n, k);
    return 0;
}


Python3




# Python program to find number of pairs
# and minimal possible value
  
from sys import maxsize
from bisect import bisect_left, bisect_right
  
# function for finding pairs and min value
def pairs(arr, n, k):
    # initialize smallest and count
    smallest = maxsize
    count = 0
    s = set()
  
    # iterate over all pairs
    s.add(arr[0])
    for i in range(1, n):
        # Find the closest elements to k - arr[i]
        sorted_s = sorted(s)
        index = bisect_left(sorted_s, k - arr[i])
        if index == len(sorted_s):
            lower = sorted_s[index - 1]
        else:
            lower = sorted_s[index]
        index = bisect_right(sorted_s, k - arr[i])
        if index == len(sorted_s):
            upper = sorted_s[index - 1]
        else:
            upper = sorted_s[index]
  
        # Find absolute value of the pairs formed
        # with closest greater and smaller elements.
        curr_min = min(abs(lower + arr[i] - k), abs(upper + arr[i] - k))
  
        # is abs value is smaller than smallest
        # update smallest and reset count to 1
        if curr_min < smallest:
            smallest = curr_min
            count = 1
        # if abs value is equal to smallest
        # increment count value
        elif curr_min == smallest:
            count += 1
        s.add(arr[i])
  
    # print result
    print("Minimal Value = ", smallest)
    print("Total Pairs = ", count)
  
# driver program
arr = [3, 5, 7, 5, 1, 9, 9]
k = 12
n = len(arr)
pairs(arr, n, k)
  
# This code is contributed by vikramshirsath177.


Java




import java.util.*;
  
class Main {
    // function for finding pairs and min value
    static void pairs(final int[] arr,final int n,final int k) {
        // initialize smallest and count
        int smallest = Integer.MAX_VALUE, count = 0;
        Set<Integer> s = new TreeSet<>();
  
        // iterate over all pairs
        s.add(arr[0]);
        for (int i = 1; i < n; i++) {
            // Find the closest elements to  k - arr[i]
            int lower = Integer.MIN_VALUE;
            int upper = Integer.MAX_VALUE;
            for (Integer x : s) {
                if (x <= (k - arr[i]) && x >= lower) {
                   lower = x;
                 }
                if (x >= (k - arr[i]) && x <= upper) {
                    upper = x;
                 }
             }
  
            // Find absolute value of the pairs formed
            // with closest greater and smaller elements.
            int curr_min = Math.min(Math.abs(lower + arr[i] - k), Math.abs(upper + arr[i] - k));
  
            // is abs value is smaller than smallest
            // update smallest and reset count to 1
            if (curr_min < smallest) {
                smallest = curr_min;
                count = 1;
            }
  
            // if abs value is equal to smallest
            // increment count value
            else if (curr_min == smallest)
                count++;
            s.add(arr[i]);
  
        } // print result
  
        System.out.println("Minimal Value = " + smallest);
        System.out.println("Total Pairs = " + count);
    }
  
    // driver program
    public static void main(String[] args) {
        int[] arr = {3, 5, 7, 5, 1, 9, 9};
        int k = 12;
        int n = arr.length;
        pairs(arr, n, k);
    }
}


Javascript




function pairs(arr, n, k) {
    // initialize smallest and count
    let smallest = Number.MAX_SAFE_INTEGER;
    let count = 0;
    let s = new Set();
   
    // iterate over all pairs
    s.add(arr[0]);
    for (let i = 1; i < n; i++) {
        // Find the closest elements to  k - arr[i]
        let lower = [...s].find((element) => element >= k - arr[i]);
        let upper = [...s].find((element) => element >= k - arr[i]);
   
        // Find absolute value of the pairs formed
        // with closest greater and smaller elements.
        let curr_min = Math.min(Math.abs(lower + arr[i] - k), Math.abs(upper + arr[i] - k));
   
        // if abs value is smaller than smallest
        // update smallest and reset count to 1
        if (curr_min < smallest) {
            smallest = curr_min;
            count = 1;
        }
        // if abs value is equal to smallest
        // increment count value
        else if (curr_min === smallest)
            count++;
        s.add(arr[i]);
    }
   
    // print result
    console.log(`Minimal Value = ${smallest}`);
    console.log(`Total Pairs = ${count}`);
}
   
// driver program
let arr = [3, 5, 7, 5, 1, 9, 9];
let k = 12;
let n = arr.length;
pairs(arr, n, k);


C#




using System;
using System.Collections.Generic;
using System.Linq;
  
class Program
{
    // function for finding pairs and min value
    static void pairs(int[] arr, int n, int k)
    {
        // initialize smallest and count
        int smallest = int.MaxValue, count = 0;
        SortedSet<int> s = new SortedSet<int>();
  
        // iterate over all pairs
        s.Add(arr[0]);
        for (int i = 1; i < n; i++)
        {
            // Find the closest elements to k - arr[i]
            int lower = s.Where(e => e >= k - arr[i]).DefaultIfEmpty(int.MinValue).First();
            int upper = s.Where(e => e > k - arr[i]).DefaultIfEmpty(int.MaxValue).First();
  
            // Find absolute value of the pairs formed
            // with closest greater and smaller elements.
            int curr_min = Math.Min(Math.Abs(lower + arr[i] - k), Math.Abs(upper + arr[i] - k));
  
            // if abs value is smaller than smallest
            // update smallest and reset count to 1
            if (curr_min < smallest)
            {
                smallest = curr_min;
                count = 1;
            }
            // if abs value is equal to smallest
            // increment count value
            else if (curr_min == smallest)
            {
                count++;
            }
            s.Add(arr[i]);
        }
  
        // print result
        Console.WriteLine("Minimal Value = " + smallest);
        Console.WriteLine("Total Pairs = " + count);
    }
  
    // driver program
    static void Main(string[] args)
    {
        int[] arr = { 3, 5, 7, 5, 1, 9, 9 };
        int k = 12;
        int n = arr.Length;
        pairs(arr, n, k);
    }
}


Output

Minimal Value = 0
Total Pairs = 4

Time Complexity : O(n Log n)
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Find the maximum possible value of the minimum value of modified array
Given an array of size [Tex]N [/Tex]and a number [Tex]S [/Tex]. The task is to modify the given array such that: The difference between the sum of the array elements before and after modification is exactly equal to S.Modified array elements should be non-negative.The minimum value in the modified array must be maximized.To modify the given array,
9 min read
Minimum value possible of a given function from the given set
Given a set Sn that represents a finite set {1, 2, 3, ....., n}. Zn denotes the set of all subsets of Sn which contains exactly 2 elements. The task is to find the value of F(n). [Tex]F(n) = \sum_{X\in Z_n }min(X) [/Tex] Examples: Input: N = 3 Output: 4 For n=3 we get value 1, 2 times and 2, 1 times thus the answer would be 1 * 2 + 2 * 1 = 4. Input
3 min read
Modify array by replacing every array element with minimum possible value of arr[j] + |j - i|
Given an array arr[] of size N, the task is to find a value for each index such that the value at index i is arr[j] + |j - i| where 1 ? j ? N, the task is to find the minimum value for each index from 1 to N. Example: Input: N = 5, arr[] = {1, 4, 2, 5, 3}Output: {1, 2, 2, 3, 3}Explanation: arr[0] = arr[0] + |0-0| = 1arr[1] = arr[0] + |0-1| = 2arr[2
11 min read
Minimize value of a given function for any possible value of X
Given an array A[] consisting of N integers(1-based indexing), the task is to find the minimum value of the function [Tex]\sum_{i = 1}^{N}(A[i] - (X + i)) [/Tex] for any possible value of X. Examples: Input: A[] = {1, 2, 3, 4} Output: 0Explanation:Consider the value of X as 0, then the value of the given function is (1 - 1 + 2 - 2 + 3 - 3 + 4 - 4)
6 min read
Minimum positive integer value possible of X for given A and B in X = P*A + Q*B
Given values of A and B, find the minimum positive integer value of X that can be achieved in the equation X = P*A + P*B, Here P and Q can be zero or any positive or negative integer. Examples: Input: A = 3 B = 2 Output: 1 Input: A = 2 B = 4 Output: 2 Basically we need to find P and Q such that P*A > P*B and P*A - P*B is minimum positive integer
3 min read
Minimum difference between maximum and minimum value of Array with given Operations
Given an array arr[] and an integer K. The following operations can be performed on any array element: Multiply the array element with K.If the element is divisible by K, then divide it by K. The above two operations can be applied any number of times including zero on any array element. The task is to find the minimum difference possible between t
9 min read
Minimum LCM and GCD possible among all possible sub-arrays
Given an array arr[] of N positive integers, the task is to find the minimum LCM and GCD between elements of all possible sub-array.Examples: Input: arr[] = {4, 4, 8} Output: LCM = 4, GCD = 4 All possible sub-arrays are: {4} -> LCM = 4, GCD = 4 {8} -> LCM = 8, GCD = 8 {4, 8} -> LCM = 8, GCD = 4Input: arr[] = {2, 66, 14, 521} Output: LCM =
6 min read
Minimum possible value of D which when added to or subtracted from K repeatedly obtains every array element
Given an array arr[] of size N and an integer K, the task is to find the maximum possible value of D, such that every array element can be obtained, starting from the initial value of K, by either changing K to K - D or K + D at each step. Examples: Input: arr[ ] = {1, 7, 11}, K = 3Output: 2Explanation:Considering the value of D to be 2, every arra
6 min read
Flip minimum signs of array elements to get minimum sum of positive elements possible
Given an array of positive elements, you have to flip the sign of some of its elements such that the resultant sum of the elements of array should be minimum non-negative (as close to zero as possible). Return the minimum no. of elements whose sign needs to be flipped such that the resultant sum is minimum non-negative. Note that the sum of all the
12 min read
Find the value of N when F(N) = f(a)+f(b) where a+b is the minimum possible and a*b = N
Given an integer N, the task is to find the value of F(N) if: F(1) = 0F(2) = 2F(N) = 0, if N is odd prime.F(N) = F(a) + F(b), where a and b are factors of N and (a + b) is minimum among all factors. Also, a * b = N Examples: Input: N = 5 Output: 0 Since 5 is an odd prime.Input: N = 4 Output: 4 4 can be written as 2 * 2, hence f(2) + f(2) = 4Input:
4 min read
Maximize Sum possible by subtracting same value from all elements of a Subarray of the given Array
Given an array a[] consisting of N integers, the task is to find the maximum possible sum that can be achieved by deducting any value, say X, from all elements of a subarray. Examples: Input: N = 3, a[] = {80, 48, 82} Output: 144 Explanation: 48 can be deducted from each array element. Therefore, sum obtained = 48 * 3 = 144Input: N = a[] = {8, 40,
11 min read
Maximum possible value of array elements that can be made based on given capacity conditions
Given two arrays arr[] and cap[] both consisting of N positive integers such that the ith element cap[i] denotes the capacity of arr[i], the task is to find the maximum possible value of array elements that can be made such that it is allowed to decrease an array element arr[i] by some arbitrary value and increment any of its adjacent element by th
5 min read
Largest value of K that a set of all possible subset-sum values of given Array contains numbers [0, K]
Given an array arr[] of N integers, the task is to find the maximum count of K, i.e, consecutive integers from 0 to K, that is present in the set S, where S contains all the possible subset-sum values of the array arr[]. Examples: Input: arr[] = {1, 3}Output: 2Explanation: The possible subsets are {}, {1}, {3}, {1, 3} and their respective sums are
6 min read
Minimum size of Array possible with given sum and product values
Given two positive integers S and P, the task is to find the minimum possible size of the array such that the sum of elements is S and the product of the elements is P. If there doesn't exist any such array, then print "-1". Examples: Input: S = 5, P = 6Output: 2Explanation: The valid array can be {2, 3}, which is of minimum size. Input: S = 5, P =
4 min read
Minimize operations to make minimum value of one array greater than maximum value of the other
Given two arrays A[] and B[] consisting of N and M integers, the task is to find the minimum number of operations required to make the minimum element of the array A[] at least the maximum element of the array B[] such that in each operation any array element A[] can be incremented by 1 or any array element B[] can be decremented by 1. Examples: In
6 min read
Minimum absolute value of (K – arr[i]) for all possible values of K over the range [0, N – 1]
Given a positive integer N and a sorted array arr[] consisting of M integers, the task is to find the minimum absolute value of (K - arr[i]) for all possible values of K over the range [0, N - 1]. Examples: Input: N = 5, arr[] = {0, 4}Output: 0 1 2 1 0Explanation:Below are the possible minimum value for all possible values of K over the range [0, N
9 min read
Minimum possible value of (i * j) % 2019
Given two integers L and R, the task is to find the minimum possible value of (i * j) % 2019 where L ? i < j ? RExamples: Input: L = 2020, R = 2040 Output: 2 (2020*2021)%2019 = 2Input: L = 3, R = 4 Output: 12 Approach: If R - L ? 2019 then answer is 0 as we will get a number in the range which is divisible by 2019 which gives remainder 0.If R -
4 min read
Minimum possible value of max(A, B) such that LCM(A, B) = C
Given an integer C, the task is to find the minimum possible value of max(A, B) such that LCM(A, B) = C.Examples: Input: C = 6 Output: 3 max(1, 6) = 6 max(2, 3) = 3 and min(6, 3) = 3Input: C = 9 Output: 9 Approach: An approach to solve this problem is to find all the factors of the given number using the approach discussed in this article and then
6 min read
Transform N to Minimum possible value
Given two numbers and N and D. Apply any of two below operations to N: add D to Nchange N to digitsum(N), where digitsum(N) is the sum of digits of N The task is to transform N to the minimum possible value. Print the minimum possible value of N and the number of times the given operations applied(any one of them). The number of operations must be
9 min read
Minimum possible value of Summation of |A[i] - A[i+K]|
Given an array arr[] of N integers and an integer K, the task is to find the minimum possible value of summation of |A[i] - A[i+K]| for any permutation of array arr[] (for all the indices from 0 to N - K - 1) Examples: Input: N = 4, arr = {1, 2, 3, 4}, K = 2Output: 2Explanation: For the permutation {1, 3, 2, 4}, for i = 0 the value of | A[0] - A[2]
7 min read
Minimum possible value of x so that Gcd of x is 1 with each element
Given an array arr[], the task is to find the minimum positive integer x (x > 1) such that for every ai for (0 ≤ i ≤ n-1), gcd(ai, x) = 1. Examples: Input: item[] = [10, 3, 1]Output: 7Explanation: gcd(10, 7) = 1gcd(3, 7) = 1gcd(1, 7) = 1 Input: item[] = [2, 4, 6]Output: 5Explanation: gcd(2, 5) = 1gcd(4, 5) = 1gcd(6, 5) = 1 Approach: The problem
8 min read
Minimize value of x that minimizes value of |a1−x|^c+|a2−x|^c+···+|an−x|^c for value of c as 1 and 2
Given an array arr[] of N elements, the task is to find the value of x that minimizes the value of expression for c = 1. |a1−x|c+|a2−x|c+···+|an−x|c = |a1−x|+|a2−x|+···+|an−x| Examples: Input: arr[] = { 1, 2, 9, 2, 6 } Output: 2Explanation: The best solution is to select x = 2 which produces the sum |1−2| + |2−2| + |9−2| + |2−2| + |6−2| = 12 , whic
9 min read
Minimum product of maximum and minimum element over all possible subarrays
Given an array arr[] consisting of N positive integers, the task is to find the minimum product of maximum and minimum among all possible subarrays. Examples: Input: arr[] = {6, 4, 5, 6, 2, 4}Output: 8Explanation:Consider the subarray {2, 4}, the product of minimum and maximum for this subarray is 2*4 = 8, which is minimum among all possible subarr
4 min read
Minimize sum of minimum and second minimum elements from all possible triplets
Given an array arr[], the task is to minimize the sum of minimum and second minimum elements from all possible triplets. One element can be a part of exactly one triplet. Input: arr[] = {1, 2, 4, 6, 7, 8, 3}, N = 7Output: 10Explanation: Here two triplets are formed as the size of arr[] is 7 and 7/3 = 2.Triplet 1 - {1, 6, 3} -> Two minimum elemen
5 min read
Reduce array to longest sorted array possible by removing either half of given array in each operation
Given an array arr[] of size N (always power of 2), the task is to find the length of the longest sorted array to which the given array can be reduced by removing either half of the array at each operation. Examples: Input: arr[] = { 11, 12, 1, 2, 13, 14, 3, 4 }Output: 2 Explanation: Removal of the first half of arr[] modifies arr[] to {13, 14, 3,
8 min read
Minimum possible sum of array elements after performing the given operation
Given an array arr[] of size N and a number X. If any sub array of the array(possibly empty) arr[i], arr[i+1], ... can be replaced with arr[i]/x, arr[i+1]/x, .... The task is to find the minimum possible sum of the array which can be obtained. Note: The given operation can only be performed once.Examples: Input: N = 3, X = 2, arr[] = {1, -2, 3} Out
9 min read
Maximise minimum element possible in Array after performing given operations
Given an array arr[] of size N. The task is to maximize the minimum value of the array after performing given operations. In an operation, value x can be chosen and A value 3 * x can be subtracted from the arr[i] element.A value x is added to arr[i-1]. andA value of 2 * x can be added to arr[i-2]. Find the maximum possible minimum element of the ar
11 min read
Minimum possible sum of prices of a Triplet from the given Array
Given an array num[] of N integers where each element is associated with a price given by another array price[], the task is to minimize the sum of price by taking a triplet such that num[i] < num[j] < num[k]. If there is no such triplet then print -1. Examples: Input: num[]={2, 4, 6, 7, 8}, price[]={10, 20, 100, 20, 40} Output: 50 Explanatio
12 min read
Find minimum possible size of array with given rules for removing elements
Given an array of numbers and a constant k, minimize size of array with following rules for removing elements. Exactly three elements can be removed at one go.The removed three elements must be adjacent in array, i.e., arr[i], arr[i+1], arr[i+2]. And the second element must be k greater than first and third element must be k greater than second, i.
11 min read
Remove minimum numbers from the array to get minimum OR value
Given an array arr[] of N positive integers, the task is to find the minimum number of elements to be deleted from the array so that the bitwise OR of the array elements get minimized. You are not allowed to remove all the elements i.e. at least one element must remain in the array.Examples: Input: arr[] = {1, 2, 3} Output: 2 All possible subsets a
5 min read
three90RightbarBannerImg