Open In App

Smallest number that can replace all -1s in an array such that maximum absolute difference between any pair of adjacent elements is minimum

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N positive integers and some elements as -1, the task is to find the smallest number, say K, such that replacing all -1s in the array by K minimizes the maximum absolute difference between any pair of adjacent elements.

Examples:

Input: arr[] = {-1, 10, -1, 12, -1}
Output: 11
Explanation:
Consider the value of K as 11. Now, replacing all array elements having value -1 to the value K(= 11) modifies the array to {11, 10, 11, 12, 11}. The maximum absolute difference among all the adjacent element is 1, which is minimum among all possible value of K.

Input: arr[] = {1, -1, 3, -1}
Output: 2

Naive Approach: The simplest approach to solve the given problem by iterating over all possible values of K from 1 check one by one which value of K gives the minimized maximum absolute difference between any two adjacent elements and print that value K

Time Complexity: O(N*K)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized based on the following observations:

  • If the absolute value of any number, say X is to be minimized from the set of numbers, the average of the minimum and maximum element of the set of is the most optimal value for X that minimizes the absolute value.
  • Therefore, the idea is to find the minimum and the maximum value of all the array elements which are adjacent to the element “-1” and print the average of the two number as the resultant value of K.

Follow the steps below to solve the problem:

  • Initialize two variables, say maxE as INT_MIN and minE as INT_MAX, to store the maximum and the minimum element among all possible values that are adjacent to “-1” in the array.
  • Traverse the given array and perform the following steps:
    • If the current element arr[i] is “-1” and the next element is not “-1”, then update the value of maxE to the maximum of maxE and arr[i + 1] and minE to the minimum of minE and arr[i + 1].
    • If the current element arr[i] is not “-1” and the next element is “-1”, then update the value of maxE to the maximum of maxE and arr[i] and minE to the minimum of minE and arr[i].
  • After completing the above steps, if the value of maxE and minE is unchanged then all array elements are “-1”, therefore, print 0 as the resultant value of K. Otherwise, print the average of minE and maxE as the resultant value of K.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the value of K to
// minimize the value of maximum absolute
// difference between adjacent elements
void findMissingValue(int arr[], int N)
{
 
    // Stores the maximum and minimum
    // among array elements that are
    // adjacent to "-1"
    int minE = INT_MAX, maxE = INT_MIN;
 
    // Traverse the given array arr[]
    for (int i = 0; i < N - 1; i++) {
 
        // If arr[i] is -1 & arr[i + 1]
        // is not -1
        if (arr[i] == -1
            && arr[i + 1] != -1) {
            minE = min(minE, arr[i + 1]);
            maxE = max(maxE, arr[i + 1]);
        }
 
        // If arr[i + 1] is -1 & arr[i]
        // is not -1
        if (arr[i] != -1
            && arr[i + 1] == -1) {
            minE = min(minE, arr[i]);
            maxE = max(maxE, arr[i]);
        }
    }
 
    // If all array element is -1
    if (minE == INT_MAX
        and maxE == INT_MIN) {
        cout << "0";
    }
 
    // Otherwise
    else {
        cout << (minE + maxE) / 2;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, -1, -1, -1, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
    findMissingValue(arr, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
 
class GFG{
     
// Function to find the value of K to
// minimize the value of maximum absolute
// difference between adjacent elements
public static void findMissingValue(int arr[], int N)
{
     
    // Stores the maximum and minimum
    // among array elements that are
    // adjacent to "-1"
    int minE = Integer.MAX_VALUE,
        maxE = Integer.MIN_VALUE;
 
    // Traverse the given array arr[]
    for(int i = 0; i < N - 1; i++)
    {
         
        // If arr[i] is -1 & arr[i + 1]
        // is not -1
        if (arr[i] == -1 && arr[i + 1] != -1)
        {
            minE = Math.min(minE, arr[i + 1]);
            maxE = Math.max(maxE, arr[i + 1]);
        }
 
        // If arr[i + 1] is -1 & arr[i]
        // is not -1
        if (arr[i] != -1 && arr[i + 1] == -1)
        {
            minE = Math.min(minE, arr[i]);
            maxE = Math.max(maxE, arr[i]);
        }
    }
 
    // If all array element is -1
    if (minE == Integer.MAX_VALUE &&
        maxE == Integer.MIN_VALUE)
    {
        System.out.println("0");
    }
 
    // Otherwise
    else
    {
        System.out.println((minE + maxE) / 2);
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, -1, -1, -1, 5 };
    int N = arr.length;
     
    findMissingValue(arr, N);
}
}
 
// This code is contributed by Potta Lokesh


Python3




# Python 3 program for the above approach
import sys
 
# Function to find the value of K to
# minimize the value of maximum absolute
# difference between adjacent elements
def findMissingValue(arr, N):
   
    # Stores the maximum and minimum
    # among array elements that are
    # adjacent to "-1"
    minE = sys.maxsize
    maxE = -sys.maxsize - 1
 
    # Traverse the given array arr[]
    for i in range(N - 1):
       
        # If arr[i] is -1 & arr[i + 1]
        # is not -1
        if (arr[i] == -1 and arr[i + 1] != -1):
            minE = min(minE, arr[i + 1])
            maxE = max(maxE, arr[i + 1])
 
        # If arr[i + 1] is -1 & arr[i]
        # is not -1
        if (arr[i] != -1 and arr[i + 1] == -1):
            minE = min(minE, arr[i])
            maxE = max(maxE, arr[i])
 
    # If all array element is -1
    if (minE == sys.maxsize and maxE == -sys.maxsize-1):
        print("0")
 
    # Otherwise
    else:
        print((minE + maxE) // 2)
 
# Driver Code
if __name__ == '__main__':
    arr = [1, -1, -1, -1, 5]
    N = len(arr)
    findMissingValue(arr, N)
     
    # This code is contributed by SURENDRA_GANGWAR.


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find the value of K to
// minimize the value of maximum absolute
// difference between adjacent elements
public static void findMissingValue(int[] arr, int N)
{
     
    // Stores the maximum and minimum
    // among array elements that are
    // adjacent to "-1"
    int minE = Int32.MaxValue,
        maxE = Int32.MinValue;
 
    // Traverse the given array arr[]
    for(int i = 0; i < N - 1; i++)
    {
         
        // If arr[i] is -1 & arr[i + 1]
        // is not -1
        if (arr[i] == -1 && arr[i + 1] != -1)
        {
            minE = Math.Min(minE, arr[i + 1]);
            maxE = Math.Max(maxE, arr[i + 1]);
        }
 
        // If arr[i + 1] is -1 & arr[i]
        // is not -1
        if (arr[i] != -1 && arr[i + 1] == -1)
        {
            minE = Math.Min(minE, arr[i]);
            maxE = Math.Max(maxE, arr[i]);
        }
    }
 
    // If all array element is -1
    if (minE == Int32.MaxValue &&
        maxE == Int32.MinValue)
    {
        Console.WriteLine("0");
    }
 
    // Otherwise
    else
    {
        Console.WriteLine((minE + maxE) / 2);
    }
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, -1, -1, -1, 5 };
    int N = arr.Length;
 
    findMissingValue(arr, N);
}
}
 
// This code is contributed by rishavmahato348


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to find the value of K to
// minimize the value of maximum absolute
// difference between adjacent elements
function findMissingValue(arr, N)
{
     
    // Stores the maximum and minimum
    // among array elements that are
    // adjacent to "-1"
    let minE = Number.MAX_VALUE,
        maxE = Number.MIN_VALUE;
 
    // Traverse the given array arr[]
    for(let i = 0; i < N - 1; i++)
    {
         
        // If arr[i] is -1 & arr[i + 1]
        // is not -1
        if (arr[i] == -1 && arr[i + 1] != -1)
        {
            minE = Math.min(minE, arr[i + 1]);
            maxE = Math.max(maxE, arr[i + 1]);
        }
 
        // If arr[i + 1] is -1 & arr[i]
        // is not -1
        if (arr[i] != -1 && arr[i + 1] == -1)
        {
            minE = Math.min(minE, arr[i]);
            maxE = Math.max(maxE, arr[i]);
        }
    }
 
    // If all array element is -1
    if (minE == Number.MAX_VALUE &&
        maxE == Number.MIN_VALUE)
    {
        document.write("0");
    }
 
    // Otherwise
    else
    {
        document.write((minE + maxE) / 2);
    }
}
 
// Driver Code
let arr = [ 1, -1, -1, -1, 5 ];
let N = arr.length;
 
findMissingValue(arr, N);
 
// This code is contributed by Potta Lokesh
 
</script>


Output: 

3

 

Time Complexity: O(N), where N is the size of the input array. This is because the program iterates through the array once to find the maximum and minimum adjacent elements to “-1”, and then performs a constant number of operations to calculate and output the missing value.
Auxiliary Space: O(1),Space complexity of the program is O(1), as it uses a constant amount of extra space to store the variables minE and maxE. The size of the input array is not taken into account for space complexity, as the program does not use any additional data structures or dynamically allocate memory.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads