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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Minimize cost required to make all array elements greater than or equal to zero
Next article icon

Minimum operations required to make all elements of Array less than equal to 0

Last Updated : 20 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N positive numbers, the task is to find the minimum number of operations required to make all elements of the array less than or equal to 0. In each operation, one has to pick the minimum positive element from the array and subtract all the elements of the array from that number.

Examples:

Input: arr[] = {1, 2, 4, 2, 2, 5, 6}
Output: 5
Explanation: The explanation is mentioned in the diagram below: 
 


 


The resulting array has met the criteria as all it's elements are either less than or equal to 0 
 

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

Naive Approach: The simplest approach to solve the problem is to Traverse the array while all the elements of the array are not less than or equal to 0 and find the minimum non-zero positive element and subtract that element from the whole array.

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

Efficient Approach: The above approach can be optimized further by observing that the answer will be the number of non-zero distinct elements in the array. Follow the steps below to solve the problem:

  • Initialize a hash-map say m that stores the unique elements present in the array.
  • Iterate in the range [0, N-1] using the variable i and mark m[arr[i]] as 1.
  • Print the value of m.size() as the answer.

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 minimum number of // non-zero elements that has to be subtracted // such that all the elements are less than or 0 int distinct(vector<int> arr) {     // Hash map to mark elements true     // that are present in the array     map<int, bool> m;      // Traverse the array     for (int i = 0; i < arr.size(); i++) {         // Mark arr[i] true         m[arr[i]] = true;     }      // Finally, return the size of hashmap     return m.size(); }  // Driver Code int main() {      // Given Input     vector<int> arr = { 1, 2, 4, 2, 2, 5, 6 };      // Function Call     int ans = distinct(arr);     cout << ans << endl;     return 0; } 
Java
// Java program for the above approach import java.util.HashMap;  class GFG{      // Function to find minimum number of // non-zero elements that has to be subtracted // such that all the elements are less than or 0 public static int distinct(int[] arr)  {          // Hash map to mark elements true     // that are present in the array     HashMap<Integer,              Boolean> m = new HashMap<Integer,                                       Boolean>();      // Traverse the array     for(int i = 0; i < arr.length; i++)      {                  // Mark arr[i] true         m.put(arr[i], true);     }      // Finally, return the size of hashmap     return m.size(); }  // Driver Code public static void main(String args[]) {          // Given Input     int[] arr = { 1, 2, 4, 2, 2, 5, 6 };      // Function Call     int ans = distinct(arr);          System.out.println(ans); } }  // This code is contributed by gfgking 
Python3
# Python 3 Program for the above approach  # Function to find minimum number of # non-zero elements that has to be subtracted # such that all the elements are less than or 0 def distinct(arr):      # Hash map to mark elements true     # that are present in the array     m = {}      # Traverse the array     for i in range(len(arr)):         # Mark arr[i] true         m[arr[i]] = True      # Finally, return the size of hashmap     return len(m)   # Driver Code if __name__ == "__main__":      # Given Input     arr = [1, 2, 4, 2, 2, 5, 6]      # Function Call     ans = distinct(arr)     print(ans)      # This code is contributed by  ukasp. 
C#
// C# program for the above approach using System; using System.Collections.Generic;  class GFG{      // Function to find minimum number of // non-zero elements that has to be subtracted // such that all the elements are less than or 0 static int distinct(List<int> arr) {          // Hash map to mark elements true     // that are present in the array     Dictionary<int,                bool> m = new Dictionary<int,                                         bool>();      // Traverse the array     for(int i = 0; i < arr.Count; i++)     {                  // Mark arr[i] true         if (m.ContainsKey(arr[i]))             m[arr[i]] = true;         else             m.Add(arr[i],true);     }      // Finally, return the size of hashmap     return m.Count; }  // Driver Code public static void Main() {          // Given Input     List<int> arr = new List<int>(){ 1, 2, 4, 2, 2, 5, 6 };      // Function Call     int ans = distinct(arr);     Console.Write(ans); } }  // This code is contributed by SURENDRA_GANGWAR 
JavaScript
<script>  // JavaScript Program for the above approach   // Function to find minimum number of // non-zero elements that has to be subtracted // such that all the elements are less than or 0 function distinct(arr) {     // Hash map to mark elements true     // that are present in the array     let m = new Map();      // Traverse the array     for (let i = 0; i < arr.length; i++) {         // Mark arr[i] true         m.set(arr[i], true);     }      // Finally, return the size of hashmap     return m.size; }  // Driver Code   // Given Input let arr = [1, 2, 4, 2, 2, 5, 6];  // Function Call let ans = distinct(arr); document.write(ans + "<br>");  </script> 

Output: 
5

 

Time Complexity: O(N)
Auxiliary Space: O(N) since map takes up space equal to the length of the array hence the space used by the algorithm is linear
 


Next Article
Minimize cost required to make all array elements greater than or equal to zero

A

adityamutharia
Improve
Article Tags :
  • Hash
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Hash

Similar Reads

  • Minimum no. of operations required to make all Array Elements Zero
    Given an array of N elements and each element is either 1 or 0. You need to make all the elements of the array equal to 0 by performing the below operations: If an element is 1, You can change it's value equal to 0 then, if the next consecutive element is 1, it will automatically get converted to 0.
    12 min read
  • Minimum operation to make all elements equal in array
    Given an array consisting of n positive integers, the task is to find the minimum number of operations to make all elements equal. In each operation, we can perform addition, multiplication, subtraction, or division with any number and an array element. Examples: Input : arr[] = [1, 2, 3, 4]Output :
    11 min read
  • Minimum operations required to make every element greater than or equal to K
    Given an array of length N. The task is to convert it into a sequence in which all elements are greater than or equal to K.The only operation allowed is taking two smallest elements of the sequence and replace them by their LCM. Find the minimum number of operations required. If it is impossible to
    7 min read
  • Minimize operations required to make each element of Array equal to it's index value
    Given an array arr[] consisting of N integers, the task is to modify the array such that arr[index] = index using minimum number of operations of the following type: Choose any index i and any integer X, and add X to all the elements in the range [0, i].Choose any index i and any integer X, and chan
    7 min read
  • Minimize cost required to make all array elements greater than or equal to zero
    Given an array arr[] consisting of N integers and an integer X, the task is to find the minimum cost required to make all array elements greater than or equal to 0 by performing the following operations any number of times: Increase any array element by 1. Cost = 1.Increase all array elements by 1.
    7 min read
  • Minimum operations to make all Array elements 0 by MEX replacement
    Given an array of N integers. You can perform an operation that selects a contiguous subarray and replaces all its elements with the MEX (smallest non-negative integer that does not appear in that subarray), the task is to find the minimum number of operations required to make all the elements of th
    5 min read
  • Minimum Bitwise OR operations to make any two array elements equal
    Given an array arr[] of integers and an integer K, we can perform the Bitwise OR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two eleme
    9 min read
  • Minimum number of given operations required to reduce the array to 0 element
    Given an array arr[] of N integers. The task is to find the minimum number of given operations required to reduce the array to 0 elements. In a single operation, any element can be chosen from the array and all of its multiples get removed including itself.Examples: Input: arr[] = {2, 4, 6, 3, 4, 6,
    6 min read
  • Minimum Cost to make all array elements equal using given operations
    Given an array arr[] of positive integers and three integers A, R, M, where The cost of adding 1 to an element of the array is A,the cost of subtracting 1 from an element of the array is R andthe cost of adding 1 to an element and subtracting 1 from another element simultaneously is M. The task is t
    12 min read
  • Minimize flips on K-length subarrays required to make all array elements equal to 1
    Given a binary array arr[] of size N and a positive integer K, the task is to find the minimum number of times any subarray of size K from the given array arr[] is required to be flipped to make all array elements equal to 1. If it is not possible to do so, then print "-1". Examples: Input: arr[] =
    15+ 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