Given an array arr[] and an integer N, the task is to find a number K from the given array such that if all the elements in the arr greater than K are changed to K then the sum of all the elements in the resulting array will be N. Print -1 if it is not possible.Â
Examples:Â
Â
Input: arr[] = {3, 1, 10, 8, 4}, N = 16Â
Output: 4Â
If all the elements greater than 4 are changed to 4 then the resulting array will be {3, 1, 4, 4, 4}Â
Hence the sum will be 16 which is the required value of N.
Input: arr[] = {3, 1, 10, 8, 4}, N = 11Â
Output: -1Â
Â
Â
Approach: The idea is to use sorting to solve the above problem.Â
Â
- First, sort the array in ascending order.
- Then traverse the array and for each element arr[i].
- Assume that all the elements after it has been changed to arr[i] and calculate the sum.
- If it is equal to N then return arr[i].
- If the end of the array is reached then print -1.
Below is the implementation of the above approach:Â
Â
C++
// C++ implementation of the approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to return K such that changing// all elements greater than K to K will// make array sum N otherwise return -1int findK(int arr[], int size, int N){Â
    // Sorting the array in increasing order    sort(arr, arr + size);    int temp_sum = 0;Â
    // Loop through all the elements of the array    for (int i = 0; i < size; i++) {        temp_sum += arr[i];Â
        // Checking if sum of array equals N        if (N - temp_sum == arr[i] * (size - i - 1)) {            return arr[i];        }    }    return -1;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 3, 1, 10, 4, 8 };Â Â Â Â int size = sizeof(arr) / sizeof(int);Â Â Â Â int N = 16;Â
    cout << findK(arr, size, N);Â
    return 0;} |
Java
// Java implementation of the approach import java.util.*;Â
class GFG {         // Function to return K such that changing     // all elements greater than K to K will     // make array sum N otherwise return -1     static int findK(int arr[], int size, int N)     {              // Sorting the array in increasing order         Arrays.sort(arr);         int temp_sum = 0;              // Loop through all the elements of the array         for (int i = 0; i < size; i++)        {             temp_sum += arr[i];                  // Checking if sum of array equals N             if (N - temp_sum == arr[i] * (size - i - 1))            {                 return arr[i];             }         }         return -1;     }          // Driver code     public static void main (String[] args)    {         int []arr = { 3, 1, 10, 4, 8 };         int size = arr.length;         int N = 16;              System.out.print(findK(arr, size, N));     } }Â
// This code is contributed by AnkitRai01 |
Python
# Python3 implementation of the approachÂ
# Function to return K such that changing# all elements greater than K to K will# make array sum N otherwise return -1def findK(arr, size, N):Â
    # Sorting the array in increasing order    arr = sorted(arr)    temp_sum = 0Â
    # Loop through all the elements of the array    for i in range(size):        temp_sum += arr[i]Â
        # Checking if sum of array equals N        if (N - temp_sum == arr[i] * (size - i - 1)):            return arr[i]    return -1Â
# Driver codearr = [3, 1, 10, 4, 8]size = len(arr)N = 16Â
print(findK(arr, size, N))Â
# This code is contributed by mohit kumar 29 |
C#
// C# implementation of the above approachusing System;Â
class GFG {         // Function to return K such that changing     // all elements greater than K to K will     // make array sum N otherwise return -1     static int findK(int []arr, int size, int N)     {              // Sorting the array in increasing order         Array.Sort(arr);         int temp_sum = 0;              // Loop through all the elements of the array         for (int i = 0; i < size; i++)        {             temp_sum += arr[i];                  // Checking if sum of array equals N             if (N - temp_sum == arr[i] * (size - i - 1))            {                 return arr[i];             }         }         return -1;     }          // Driver code     public static void Main()    {         int []arr = { 3, 1, 10, 4, 8 };         int size = arr.Length;         int N = 16;              Console.Write(findK(arr, size, N));     } }Â
// This code is contributed by AnkitRai01 |
Javascript
<script>    // Javascript implementation of the approach          // Function to return K such that changing     // all elements greater than K to K will     // make array sum N otherwise return -1     function findK(arr, size, N)     {                // Sorting the array in increasing order         arr.sort(function(a, b){return a - b});        let temp_sum = 0;                // Loop through all the elements of the array         for (let i = 0; i < size; i++)        {             temp_sum += arr[i];                    // Checking if sum of array equals N             if (N - temp_sum == arr[i] * (size - i - 1))            {                 return arr[i];             }         }         return -1;     }          let arr = [ 3, 1, 10, 4, 8 ];     let size = arr.length;     let N = 16; Â
    document.write(findK(arr, size, N)); Â
// This code is contributed by divyesh07019.</script> |
4
Time Complexity: O(N * log N)
Auxiliary Space: O(1)
Approach : Binary Search
Steps:
- First sort the array in non-decreasing order.
- Then uses binary search to find the maximum value of K.
- The left and right variables are used to keep track of the range of possible values for K.
- The mid variable is the midpoint of this range.
- Inside the while loop, the code calculates the sum of the array after replacing all values greater than mid with mid.
- If this sum == N, then we have found our value of K and break out of the loop.
- If the sum is > N, we update right to be mid – 1, and if the sum is < N, we update left to be mid + 1.
- Finally, the code checks if a valid value of K was found and prints either the value of K or -1.
Below is the implementation of the above approach:
C++
// C++ implementation of the approachÂ
#include <algorithm>#include <iostream>#include <vector>using namespace std;Â
int main(){Â Â Â Â int arr[] = { 3, 1, 10, 8, 4 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â Â Â Â int N = 11;Â
    // sort the array in non-decreasing order    sort(arr, arr + n);Â
    int left = arr[0];    int right = arr[n - 1];    int K = -1;Â
    while (left <= right) {        int mid = left + (right - left) / 2;Â
        // iterate through the array, replacing all values        // greater than mid with mid        int sum = 0;        for (int i = 0; i < n; i++) {            sum += min(arr[i], mid);        }Â
        // check if the sum is equal to N        if (sum == N) {            K = mid;            break;        }        else if (sum > N) {            right = mid - 1;        }        else {            left = mid + 1;        }    }Â
    if (K == -1) {        cout << "-1" << endl;    }    else {        cout << K << endl;    }Â
    return 0;} |
Java
import java.util.Arrays;Â
public class GFG {Â Â Â Â public static void main(String[] args) {Â Â Â Â Â Â Â Â int[] arr = { 3, 1, 10, 8, 4 };Â Â Â Â Â Â Â Â int n = arr.length;Â Â Â Â Â Â Â Â int N = 11;Â
        // Sort the array in non-decreasing order        Arrays.sort(arr);Â
        int left = arr[0];        int right = arr[n - 1];        int K = -1;Â
        while (left <= right) {            int mid = left + (right - left) / 2;Â
            // Iterate through the array, replacing all values            // greater than mid with mid            int sum = 0;            for (int i = 0; i < n; i++) {                sum += Math.min(arr[i], mid);            }Â
            // Check if the sum is equal to N            if (sum == N) {                K = mid;                break;            } else if (sum > N) {                right = mid - 1;            } else {                left = mid + 1;            }        }Â
        if (K == -1) {            System.out.println("-1");        } else {            System.out.println(K);        }    }} |
Python3
# Python3 implementation of the approach  def find_max_K(arr, N):    # Sort the array in non-decreasing order    arr.sort()Â
    n = len(arr)    left = arr[0]    right = arr[n - 1]    K = -1Â
    while left <= right:        # Calculate the midpoint using integer division        mid = left + (right - left) // 2Â
        # Iterate through the array, replacing all values         # greater than mid with mid        sum = 0        for i in range(n):            sum += min(arr[i], mid)Â
        # Check if the sum is equal to N        if sum == N:            K = mid            break        elif sum > N:            # If the sum is greater than N, search in the left half            right = mid - 1        else:            # If the sum is less than N, search in the right half            left = mid + 1Â
    if K == -1:        print("-1")    else:        print(K)Â
# Driver codearr = [3, 1, 10, 8, 4]N = 11find_max_K(arr, N) |
Javascript
function binarySearch(arr, N) {Â Â Â Â arr.sort((a, b) => a - b);Â Â Â Â let left = arr[0];Â Â Â Â let right = arr[arr.length - 1];Â Â Â Â let K = -1;Â
    while (left <= right) {        let mid = left + Math.floor((right - left) / 2);        let sum = 0;Â
        for (let i = 0; i < arr.length; i++) {            sum += Math.min(arr[i], mid);        }Â
        if (sum === N) {            K = mid;            break;        } else if (sum > N) {            right = mid - 1;        } else {            left = mid + 1;        }    }Â
    return K;}Â
const arr = [3, 1, 10, 8, 4];const N = 11;Â
const result = binarySearch(arr, N);Â
if (result === -1) {Â Â Â Â console.log("-1");} else {Â Â Â Â console.log(result);} |
-1
Time Complexity: O(nlog(max – min)), where n is the size of the input array.
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
