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:
Minimize operations to make Array a permutation
Next article icon

Minimize operations to convert Array elements to 0s

Last Updated : 12 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array nums[] of length N containing non-negative integers, the task is to convert all elements from index 0 to N-2 to zero, after doing the below operations minimum number of times.

  • In one operation select two indices i and j such that i < j  and all the elements between i and j has to be non-zero, then set nums[i] = nums[i] - 1 and nums[j] = nums[j] + 1.

Examples:

Input: N = 5, nums[] = [0, 2, 0, 2, 0]
Output: 5
Explanation: We need to do 5 above given operation 
to complete the task, and the operations are:

  • Select j = 3, k = 4 nums[] becomes: [0, 2, 0, 1, 1]
  • Select j = 1, k = 2 nums[] becomes: [0, 1, 1, 1, 1]
  • Select j = 1, k = 4 nums[] becomes: [0, 0, 1, 1, 2]
  • Select j = 2, k = 4 nums[] becomes: [0, 0, 0, 1, 3]
  • Select j = 3, k = 4 nums[] becomes: [0, 0, 0, 0, 4]

Input: N = 3, nums[] = [2, 0, 0]
Output: 3
Explanation: We need to do 3 above given operation 
to complete the task, and the operations are:

  • Select j = 0, k = 1 nums[] becomes: [1, 1, 0]
  • Select j = 0, k = 2 nums[] becomes: [0, 1, 1]
  • Select j = 1, k = 2 nums[] becomes: [0, 0, 2]
 

Approach: The problem can be solved based on the following idea:

  • The possible way to convert all elements from 0 to N-2 to 0 is by reducing each element from the left by 1 and adding 1 each time to the last element, until leftmost element become zero and then moving to the next index. So the number of operations will be the sum of elements from 0 to N-2.
  • But if there is a 0 present in between then first we have to convert that 0 into a positive number, so that we can perform the operation for the elements present in the left of that 0. 
  • To convert a 0 to a positive element, 1 operation will take place, so our final answer will be the sum of elements from 0 to N-2 and the number of zeros present after the first positive element. 

Follow the steps given below to implement the approach:

  • First traverse the array till you get the first non-zero element.
    • After that if element is non-zero then update ans += nums[i]
    • Else if the element is zero then update ans += 1.
  • Traverse the given array till N-2 and calculate the required answer as mentioned above.
  • Return the calculated answer.

Below is the implementation of the above approach.

C++
// C++ Algorithm for the above approach #include <iostream> using namespace std;  // Function which returns // minimum number of operations // required to convert array // into target array int minOperations(int nums[], int N) {        // ans variable contains number of     // operations processed after traversing     // ith element     int ans = 0;     int i = 0;      // Traversing to get first non-zero element     while (i < N && nums[i] == 0)         i++;        // After getting first non-zero element we will     // apply the given operation     while (i < N - 1) {         if (nums[i] == 0)             ans++;         else             ans += nums[i];         i++;     }      // Returning the ans variable     return ans; }  // Driver Code int main() {      int N = 5;     int nums[] = { 0, 2, 0, 2, 0 };        // Function Call     int ans = minOperations(nums, N);     cout << ans;     return 0; }  // This code is contributed by Kdheeraj. 
Java
// Java algorithm of the above approach  import java.util.*;  class GFG {      // Driver Code     public static void main(String[] args)     {         int N = 5;         int[] nums = { 0, 2, 0, 2, 0 };         // Function Call         int ans = minOperations(nums, N);         System.out.println(ans);     }      // Function which returns     // minimum number of operations     // required to convert array     // into target array     public static int minOperations(int[] nums, int N)     {         // ans variable contains number of         // operations processed after traversing         // ith element         int ans = 0;         int i = 0;          // Traversing to get first non-zero element         while (i < N && nums[i] == 0)             i++;         // After getting first non-zero element we will         // apply the given operation         while (i < N - 1) {             if (nums[i] == 0)                 ans++;             else                 ans += nums[i];             i++;         }          // Returning the ans variable         return ans;     } } 
Python3
# Python code to implement the above approach  # Function which returns # minimum number of operations # required to convert array # into target array def minOperations(nums, N) :        # ans variable contains number of     # operations processed after traversing     # ith element     ans = 0     i = 0      # Traversing to get first non-zero element     while (i < N and nums[i] == 0) :         i += 1        # After getting first non-zero element we will     # apply the given operation     while (i < N - 1) :         if (nums[i] == 0) :             ans += 1         else :             ans += nums[i]         i += 1           # Returning the ans variable     return ans  # Driver Code if __name__ == "__main__":      N = 5     nums = [ 0, 2, 0, 2, 0 ]        # Function Call     ans = minOperations(nums, N)     print(ans)          # This code is contributed by sanjoy_62. 
C#
// C# program for above approach: using System; class GFG {    // Function which returns   // minimum number of operations   // required to convert array   // into target array   public static int minOperations(int[] nums, int N)   {          // ans variable contains number of     // operations processed after traversing     // ith element     int ans = 0;     int i = 0;      // Traversing to get first non-zero element     while (i < N && nums[i] == 0)       i++;     // After getting first non-zero element we will     // apply the given operation     while (i < N - 1) {       if (nums[i] == 0)         ans++;       else         ans += nums[i];       i++;     }      // Returning the ans variable     return ans;   }    // Driver Code   public static void Main()   {     int N = 5;     int[] nums = { 0, 2, 0, 2, 0 };          // Function Call     int ans = minOperations(nums, N);     Console.Write(ans);    } }  // This code is contributed by code_hunt. 
JavaScript
<script> // Javascript Algorithm for the above approach  // Function which returns // minimum number of operations // required to convert array // into target array function minOperations(nums, N) {        // ans variable contains number of     // operations processed after traversing     // ith element     let ans = 0;     let i = 0;      // Traversing to get first non-zero element     while (i < N && nums[i] == 0)         i++;        // After getting first non-zero element we will     // apply the given operation     while (i < N - 1) {         if (nums[i] == 0)             ans++;         else             ans += nums[i];         i++;     }      // Returning the ans variable     return ans; }  // Driver Code     let N = 5;     let nums = [ 0, 2, 0, 2, 0 ];        // Function Call     let ans = minOperations(nums, N);     document.write(ans);          // This code is contributed by satwik4409.     </script> 

Output
5

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


Next Article
Minimize operations to make Array a permutation
author
kdheeraj
Improve
Article Tags :
  • Greedy
  • Mathematical
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical

Similar Reads

  • Minimize cost to convert all array elements to 0
    Given two integers X and Y and a binary array arr[] of length N whose first and last element is 1, the task is to minimize the cost to convert all array elements to 0, where X and Y represent the cost of converting a subarray of all 1s to 0s and the cost of converting any element to 0 respectively.
    12 min read
  • Minimum cost to equal all elements of array using two operation
    Given an array arr[] of n positive integers. There are two operations allowed: Operation 1 : Pick any two indexes, increase value at one index by 1 and decrease value at another index by 1. It will cost a. Operation 2 : Pick any index and increase its value by 1. It will cost b. The task is to find
    8 min read
  • Minimize subtraction of Array elements to make X at most 0
    Given a number X, and an array arr[] of length N containing the N numbers. The task is to find the minimum number of operations required to make X non-positive. In one operation: Select any one number Y from the array and reduce X by Y. Then make Y = Y/2 (take floor value if Y is odd).If it is not p
    9 min read
  • Minimize increment-decrement operation on adjacent elements to convert Array A to B
    Given two arrays A[] and B[] consisting of N positive integers, the task is to find the minimum number of increment and decrements of adjacent array elements of the array A[] required to convert it to the array B[]. If it is not possible, then print "-1". Examples: Input: A[] = {1, 2}, B[] = {2, 1}O
    11 min read
  • Minimize operations to make Array a permutation
    Given an array arr of n integers. You want to make this array a permutation of integers 1 to n. In one operation you can choose two integers i (0 ≤ i < n) and x (x > 0), then replace arr[i] with arr[i] mod x, the task is to determine the minimum number of operations to achieve this goal otherw
    7 min read
  • Minimize Cost to reduce the Array to a single element by given operations
    Given an array a[] consisting of N integers and an integer K, the task is to find the minimum cost to reduce the given array to a single element by choosing any pair of consecutive array elements and replace them by (a[i] + a[i+1]) for a cost K * (a[i] + a[i+1]). Examples: Input: a[] = {1, 2, 3}, K
    15+ min read
  • Make all Array elements equal to zero in atmost m operations
    Given an integer array A[] of size N and integer k. For a fixed value p, choose an index i (1 ≤ i ≤ n) and assign A[i] = max(0, A[i] − p), this counts as one operation, and the task is to find the smallest value of p such that all the elements of the array A[] become 0 in at most k operations. Examp
    10 min read
  • Minimize the non-zero elements in the Array by given operation
    Given an array arr[] of length N, the task is to minimize the count of the number of non-zero elements by adding the value of the current element to any of its adjacent element and subtracting from the current element at most once.Examples: Input: arr[] = { 1, 0, 1, 0, 0, 1 } Output: 2 Explanation:
    5 min read
  • Minimize cost of converting all array elements to Fibonacci Numbers
    Given an array arr[] consisting of N integers, the task is to minimize the cost of converting all array elements to a Fibonacci Number, where the cost of converting a number A to B is the absolute difference between A and B. Examples: Input: arr[] = {56, 34, 23, 98, 7}Output: 13Explanation:Following
    8 min read
  • Minimum operations to convert given string into all 1s or 0s
    Given a string S containing 0s and 1s of length N with X, the task is to output the minimum operations required to convert S into either all 1s or 0s. The operation is defined as, taking two different indices i and j (1-based indexing), such that they give equal remainder when dividing from X, then
    8 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