Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Bucket Sort To Sort an Array with Negative Numbers
Next article icon

Smallest number that never becomes negative when processed against array elements

Last Updated : 19 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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 the difference of the number and the array element.
  2. If the number is smaller than an array element, then it is decreased by the 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
Recommended PracticeSmallest Non-Zero NumberTry It!

Simple Approach: A simple approach is 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.  

Implementation:

C++




// 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;
}
 
 

Java




// 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
 
 

Python3




# 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]
            else if 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
 
 

C#




// A C# program to find the smallest number
// that never becomes positive when processed
// with given array elements.
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
  
class GFG 
{
    static long suitable_num(long []a, int n)
    {
        // Finding max element in the array
        long max = a.Max();
  
        for (int x = 1; x < max; x++)
        {
  
            // Creating copy of i since it's
            // getting modified at later steps.
            long 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
    public static void Main(String []args)
    {
        long []a = { 3, 4, 3, 2, 4 };
        int n = a.Length;
        Console.Write(suitable_num(a, n));
    }
}
  
// This code is contributed by Arnab Kundu
 
 

Javascript




<script>
// A Javascript program to find the smallest number
// that never becomes positive when processed
// with given array elements.
  
    function suitable_num(a,n)
    {
        // Finding max element in the array
        let max = Math.max(...a)
    
        for (let x = 1; x < max; x++) {
    
            // Creating copy of i since it's
            // getting modified at later steps.
            let num = x;
    
            // Checking that num doesn't becomes
            // negative.
            let 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
    let a=[3, 4, 3, 2, 4];
    let n = a.length;
    document.write(suitable_num(a, n));
      
    //This code is contributed by avanitrachhadiya2155
      
</script>
 
 
Output
4

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

Efficient Approach: Efficient approach to solving 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 the 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.  

Implementation:

C++




// 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;
}
 
 

Java




// 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
 
 

Python3




# 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
 
 

C#




// Efficient C# 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
 
 

PHP




<?php
// Efficient PHP program to find the smallest 
// number that never becomes positive when 
// processed with given array elements.
  
function suitable_num(&$a, $n)
{
    $num = 0;
  
    // Calculating the suitable number 
    // at each step.
    for ($i = $n - 1; $i >= 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
?>
 
 

Javascript




<script>
  
// Efficient Javascript program to find the smallest
// number that never becomes positive when
// processed with given array elements.
function suitable_num(a,n)
{
    let num = 0;
      
    // Calculating the suitable 
    // number at each step.
    for(let i = n - 1; i >= 0; i--)
        num = Math.round((a[i] + num) / 2.0);
      
    return num;
}
  
// Driver code
let a = [ 3, 4, 3, 2, 4 ];
let n = a.length;
  
document.write(suitable_num(a, n));
  
// This code is contributed by rag2127
      
</script>
 
 
Output
4

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



Next Article
Bucket Sort To Sort an Array with Negative Numbers
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Smallest positive integer that does not divide any elements of the given array
    Given an array arr[] consisting of N positive integers, the task is to determine the smallest positive integer K such that none of the array elements is divisible by K. Examples: Input: arr[] = {3, 2, 6, 9, 2}Output: 4Explanation: None of the array elements is divisible by 4(the smallest positive).
    6 min read
  • Replace every element with the smallest of all other array elements
    Given an array arr[] which consist of N integers, the task is to replace every element by the smallest of all other elements present in the array. Examples: Input: arr[] = {1, 1, 1, 2} Output: 1 1 1 1 Input: arr[] = {4, 2, 1, 3} Output: 1 1 2 1 Naive Approach: The simplest approach is to find the sm
    12 min read
  • Minimum number of changes such that elements are first Negative and then Positive
    Given an array arr[] of size N. The task is to find the minimum number of changes required to convert the array such that for any index 0 ? k < N, the elements in the array upto k-th index will be less than zero and after k-th index will be greater than zero.That is: arr[0] < 0, arr[1] < 0,
    7 min read
  • Find the smallest positive number missing from an unsorted array : Hashing Implementation
    Given an unsorted array with both positive and negative elements including 0. The task is to find the smallest positive number missing from the array in O(N) time. Examples: Input: arr[] = {-5, 2, 0, -1, -10, 15} Output: 1 Input: arr[] = {0, 1, 2, 3, 4, 5} Output: 6 Input: arr[] = {1, 1, 1, 0, -1, -
    5 min read
  • Bucket Sort To Sort an Array with Negative Numbers
    We have discussed bucket sort in the main post on Bucket Sort . Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the problem of sorting a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across th
    9 min read
  • Remove minimum elements from the array such that 2*min becomes more than max
    Given an unsorted array, arr[]. The task is to find the minimum number of removals required such that twice the minimum element in the array is greater than or equal to the maximum in the array. Examples: Input: arr[] = [4, 5, 100, 9, 10, 11, 12, 15, 200]Output: 4Explanation: In the given array 4 el
    7 min read
  • Smallest greater elements in whole array
    An array is given of n length, and we need to calculate the next greater element for each element in the given array. If the next greater element is not available in the given array then we need to fill '_' at that index place. Examples : Input : 6 3 9 8 10 2 1 15 7 Output : 7 6 10 9 15 3 2 _ 8 Here
    11 min read
  • Find ratio of zeroes, positive numbers and negative numbers in the Array
    Given an array a of integers of size N integers, the task is to find the ratio of positive numbers, negative numbers and zeros in the array up to four decimal places. Examples: Input: a[] = {2, -1, 5, 6, 0, -3} Output: 0.5000 0.3333 0.1667 There are 3 positive, 2 negative, and 1 zero. Their ratio wo
    7 min read
  • Smallest possible integer to be added to N-1 elements in array A such that elements of array B are present in A
    Given two arrays A[] of length N and B[] of length N-1, the task is to find the smallest positive integer X that is added to every element of A[] except one element, so that all the elements of array B[] are present in array A[]. Assume that finding X is always possible. Examples: Input: A[] = {1, 4
    7 min read
  • Largest number having both positive and negative values present in the array
    Given an array arr[] consisting of N integers, the task is to find the largest number K (> 0) such that both the values K and -K are present in the given array arr[]. If no such number exists, then print -1. Examples: Input: arr[] = {3, 2, -2, 5, -3}Output: 3 Input: arr[] = {1, 2, 3, -4}Output: -
    14 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences