Smallest number that never becomes negative when processed against array elements

Given an array of size n your goal is to find a number such that when the number is processed against each array element starting from the 0th index till the (n-1)-th index under the conditions given below, it never becomes negative.

  1. If the number is greater than an array element, then it is increased by difference of the number and the array element.
  2. If the number is smaller than an array element, then it is decreased by difference of the number and the array element.

Examples:

Input : arr[] = {3 4 3 2 4}
Output : 4
Explanation : 
If we process 4 from left to right
in given array, we get following :
When processed with 3, it becomes 5.
When processed with 5, it becomes 6
When processed with 3, it becomes 9
When processed with 2, it becomes 16
When processed with 4, it becomes 28
We always get a positive number. For 
all values lower than 4, it would
become negative for some value of the 
array.

Input: arr[] = {4 4}
Output : 3
Explanation : 
When processed with 4, it becomes 2
When processed with next 4, it becomes 1

Simple Approach: A simple approach is be to find the maximum element in the array and test against each number starting from 1 till the maximum element, that it crosses the whole array with 0 value or not.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the smallest number
// that never becomes positive when processed
// with given array elements.
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
  
ll suitable_num(ll a[], int n)
{
    // Finding max element in the array
    ll max = *max_element(a, a + n); 
  
    for (int x = 1; x < max; x++) {
  
        // Creating copy of i since it's  
        // getting modified at later steps.
        int num = x; 
  
        // Checking that num doesn't becomes
        // negative.
        int j;
        for (j = 0; j < n; j++) 
        {  
            if (num > a[j])
                num += (num - a[j]);
            else if (a[j] > num)
                num -= (a[j] - num);
            if (num < 0)
                break;
        }
  
        if (j == n) 
            return x;        
    }
  
    return max;
}
  
// Driver code
int main()
{
    ll a[] = { 3, 4, 3, 2, 4 };
    int n = sizeof(a)/(sizeof(a[0])); 
    cout << suitable_num(a, n);
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Java program to find the smallest number
// that never becomes positive when processed
// with given array elements.
import java.util.Arrays;
public class Largest_Number_NotNegate 
{
    static long suitable_num(long a[], int n)
    {
        // Finding max element in the array
        long max = Arrays.stream(a).max().getAsLong();
  
        for (int x = 1; x < max; x++) {
  
            // Creating copy of i since it's
            // getting modified at later steps.
            int num = x;
  
            // Checking that num doesn't becomes
            // negative.
            int j;
            for (j = 0; j < n; j++) {
                if (num > a[j])
                    num += (num - a[j]);
                else if (a[j] > num)
                    num -= (a[j] - num);
                if (num < 0)
                    break;
            }
  
            if (j == n)
                return x;
        }
  
        return max;
    }
      
    // Driver program to test above method
    public static void main(String[] args) {
  
        long a[] = { 3, 4, 3, 2, 4 };
        int n = a.length;
        System.out.println(suitable_num(a, n));
    }
}
// This code is contributed by Sumit Ghosh
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find the smallest number
# that never becomes positive when processed
# with given array elements.
def suitable_num(a):
    mx = max(a)
      
    for x in range(1, mx):
          
        # Creating copy of i since it's  
        # getting modified at later steps.
        num = x
          
        # Checking that num doesn't becomes
        # negative.
        j = 0;
        while j < len(a):
            if num > a[j]:
                num += num - a[j]
            elif a[j] > num:
                num -= (a[j] - num)
            if num < 0:
                break
            j += 1
        if j == len(a):
            return x
    return mx
  
# Driver code
a =[ 3, 4, 3, 2, 4 ]
print suitable_num(a)
  
# This code is contributed by Sachin Bisht
chevron_right


Output:
4

Time Complexity: O (n^2)
Auxiliary Space: O (1)

Efficient Approach: Efficient approach to solve this problem would be to use the fact that when you reach the last array element, the value with which we started can be at least 0, which means suppose last array element is a[n-1] then the value at a[n-2] must be greater than or equal to a[n-1]/2.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Efficient C++ program to find the smallest 
// number that never becomes positive when 
// processed with given array elements.
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
  
ll suitable_num(ll a[], int n)
{
    ll num = 0;
  
    // Calculating the suitable number at each step.
    for (int i = n - 1; i >= 0; i--) 
        num = round((a[i] + num) / 2.0);
  
    return num;
}
  
// Driver code
int main()
{
    ll a[] = { 3, 4, 3, 2, 4 };
    int n = sizeof(a)/(sizeof(a[0])); 
    cout << suitable_num(a, n);
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Efficient Java program to find the smallest 
// number that never becomes positive when 
// processed with given array elements.
public class Largest_Number_NotNegate {
    static long suitable_num(long a[], int n) {
        long num = 0;
  
        // Calculating the suitable number at each step.
        for (int i = n - 1; i >= 0; i--)
            num = Math.round((a[i] + num) / 2.0);
  
        return num;
    }
  
    // Driver Program to test above function
    public static void main(String[] args) {
  
        long a[] = { 3, 4, 3, 2, 4 };
        int n = a.length;
        System.out.println(suitable_num(a, n));
  
    }
}
// This code is contributed by Sumit Ghosh
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Efficient Python program to find the smallest 
# number that never becomes positive when 
# processed with given array elements.
def suitable_num(a):
    num = 0
      
    # Calculating the suitable number at each step.
    i = len(a) - 1
    while i >= 0:
        num = round((a[i] + num) / 2.0)
      
        i -= 1
    return int(num)
  
# Driver code
a = [ 3, 4, 3, 2, 4 ]
print suitable_num(a)
  
# This code is contributed by Sachin Bisht
chevron_right

// Efficient Java program to find the smallest
// number that never becomes positive when
// processed with given array elements.
using System;

class GFG
{
static long suitable_num(long[] a, int n)
{
long num = 0;

// Calculating the suitable number
// at each step.
for (int i = n – 1; i >= 0; i–)
num = (long)Math.Round((a[i] + num) / 2.0,
MidpointRounding.AwayFromZero);

return num;
}

// Driver Code
public static void Main()
{
long[] a = { 3, 4, 3, 2, 4 };
int n = a.Length;
Console.Write(suitable_num(a, n));
}
}

// This code is contributed by ita_c

= 0; $i–)
$num = round(($a[$i] + $num) / 2.0);

return $num;
}

// Driver code
$a = array( 3, 4, 3, 2, 4 );
$n = sizeof($a);
echo suitable_num($a, $n);

// This code is contributed by ita_c
?>


Output:
4

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

This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Reference: https://www.hackerrank.com/challenges/chief-hopper

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Improved By : Ita_c



Article Tags :
Practice Tags :