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:
Minimum steps required to reduce all array elements to 1 based on given steps
Next article icon

Minimum Decrements on Subarrays required to reduce all Array elements to zero

Last Updated : 11 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N non-negative integers, the task is to find the minimum number of subarrays that needs to be reduced by 1 such that all the array elements are equal to 0.

Example:

Input: arr[] = {1, 2, 3, 2, 1}
Output: 3
Explanation: 
Operation 1: {1, 2, 3, 2, 1} -> {0, 1, 2, 1, 0} 
Operation 2: {0, 1, 2, 1, 0} -> {0, 0, 1, 0, 0} 
Operation 3: {0, 0, 1, 0, 0} -> {0, 0, 0, 0, 0}

Input: arr[] = {5, 4, 3, 4, 4}
Output: 6
Explanation: 
{5, 4, 3, 4, 4} -> {4, 3, 2, 3, 3} -> {3, 2, 1, 2, 2} -> {2, 1, 0, 1, 1} -> {2, 1, 0, 0, 0} -> {1, 0, 0, 0, 0} -> {0, 0, 0, 0, 0} 
 

Approach: 
This can be optimally done by traversing the given array from index 0, finding the answer up to index i, where 0 ? i < N. If arr[i] ? arr[i+1], then (i + 1)th element can be included in every subarray operation of ith element, thus requiring no extra operations. If arr[i] < arr[i + 1], then (i + 1)th element can be included in every subarray operation of ith element and after all operations, arr[i+1] becomes arr[i+1]-arr[i]. Therefore, we need arr[i+1]-arr[i] extra operations to reduce it zero.

Follow the below steps to solve the problem:

  • Add the first element arr[0] to answer as we need at least arr[0] to make the given array 0.
  • Traverse over indices [1, N-1] and for every element, check if it is greater than the previous element. If found to be true, add their difference to the answer.

Below is the implementation of above approach:

C++




// C++ Program to implement 
// the above approach 
#include <bits/stdc++.h> 
using namespace std; 
  
// Function to count the minimum 
// number of subarrays that are 
// required to be decremented by 1 
int min_operations(vector<int>& A) 
{ 
    // Base Case 
    if (A.size() == 0) 
        return 0; 
  
    // Initialize ans to first element 
    int ans = A[0]; 
  
    for (int i = 1; i < A.size(); i++) { 
  
        // For A[i] > A[i-1], operation 
        // (A[i] - A[i - 1]) is required 
        ans += max(A[i] - A[i - 1], 0); 
    } 
  
    // Return the answer 
    return ans; 
} 
  
// Driver Code 
int main() 
{ 
    vector<int> A{ 1, 2, 3, 2, 1 }; 
  
    cout << min_operations(A) << "\n"; 
  
    return 0; 
} 
 
 

Java




// Java Program to implement 
// the above approach 
import java.io.*; 
  
class GFG { 
  
    // Function to count the minimum 
    // number of subarrays that are 
    // required to be decremented by 1 
    static int min_operations(int A[], int n) 
    { 
        // Base Case 
        if (n == 0) 
            return 0; 
  
        // Initializing ans to first element 
        int ans = A[0]; 
        for (int i = 1; i < n; i++) { 
  
            // For A[i] > A[i-1], operation 
            // (A[i] - A[i - 1]) is required 
            if (A[i] > A[i - 1]) { 
                ans += A[i] - A[i - 1]; 
            } 
        } 
  
        // Return the count 
        return ans; 
    } 
  
    // Driver Code 
    public static void main(String[] args) 
    { 
        int n = 5; 
        int A[] = { 1, 2, 3, 2, 1 }; 
        System.out.println(min_operations(A, n)); 
    } 
} 
 
 

Python




# Python Program to implement 
# the above approach 
  
# Function to count the minimum 
# number of subarrays that are 
# required to be decremented by 1 
def min_operations(A): 
  
    # Base case 
    if len(A) == 0: 
        return 0
  
    # Initializing ans to first element 
    ans = A[0] 
    for i in range(1, len(A)): 
  
        if A[i] > A[i-1]: 
            ans += A[i]-A[i-1] 
  
    return ans 
  
  
# Driver Code 
A = [1, 2, 3, 2, 1] 
print(min_operations(A)) 
 
 

C#




// C# program to implement
// the above approach
using System;
  
class GFG{
  
// Function to count the minimum
// number of subarrays that are
// required to be decremented by 1
static int min_operations(int[] A, int n)
{
      
    // Base Case
    if (n == 0)
        return 0;
  
    // Initializing ans to first element
    int ans = A[0];
      
    for(int i = 1; i < n; i++) 
    {
          
        // For A[i] > A[i-1], operation
        // (A[i] - A[i - 1]) is required
        if (A[i] > A[i - 1]) 
        {
            ans += A[i] - A[i - 1];
        }
    }
      
    // Return the count
    return ans;
}
  
// Driver Code
public static void Main()
{
    int n = 5;
    int[] A = { 1, 2, 3, 2, 1 };
      
    Console.WriteLine(min_operations(A, n));
}
}
  
// This code is contributed by bolliranadheer
 
 

Javascript




<script>
  
// Javascript program to implement 
// the above approach 
  
// Function to count the minimum 
// number of subarrays that are 
// required to be decremented by 1 
function min_operations(A) 
{ 
      
    // Base Case 
    if (A.length == 0) 
        return 0; 
  
    // Initialize ans to first element 
    let ans = A[0]; 
  
    for(let i = 1; i < A.length; i++)
    { 
          
        // For A[i] > A[i-1], operation 
        // (A[i] - A[i - 1]) is required 
        ans += Math.max(A[i] - A[i - 1], 0); 
    } 
  
    // Return the answer 
    return ans; 
} 
  
// Driver Code 
let A = [ 1, 2, 3, 2, 1 ]; 
document.write(min_operations(A)); 
  
// This code is contributed by subhammahato348
  
</script>
 
 

Output:

3

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

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Minimum steps required to reduce all array elements to 1 based on given steps

D

dp82
Improve
Article Tags :
  • Arrays
  • Competitive Programming
  • DSA
  • Greedy
  • Mathematical
  • Searching
  • subarray
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • Searching

Similar Reads

  • Minimize subarray increments/decrements required to reduce all array elements to 0
    Given an array arr[], select any subarray and apply any one of the below operations on each element of the subarray: Increment by oneDecrement by one The task is to print the minimum number of above-mentioned increment/decrement operations required to reduce all array elements to 0. Examples: Input:
    5 min read
  • Minimum steps required to reduce all the elements of the array to zero
    Given an array arr[] of positive integers, the task is to find the minimum steps to reduce all the elements to 0. In a single step, -1 can be added to all the non-zero elements of the array at the same time.Examples: Input: arr[] = {1, 5, 6} Output: 6 Operation 1: arr[] = {0, 4, 5} Operation 2: arr[
    4 min read
  • Minimum steps required to reduce all array elements to 1 based on given steps
    Given an array arr[] of size N. The task is to find the minimum steps required to reduce all array elements to 1. In each step, perform the following given operation: Choose any starting index, say i, and jump to the (arr[i] + i)th index, reducing ith as well as (arr[i] + i)th index by 1, follow thi
    8 min read
  • Maximize pair decrements required to reduce all array elements except one to 0
    Given an array arr[] consisting of N distinct elements, the task is to find the maximum number of pairs required to be decreased by 1 in each step, such that N - 1 array elements are reduced to 0 and the remaining array element is a non-negative integer. Examples: Input: arr[] = {1, 2, 3}Output: 3Ex
    13 min read
  • Minimum number of decrements by 1 required to reduce all elements of a circular array to 0
    Given an circular array arr[] consisting of N integers, the task is to find the minimum number of operations to reduce all elements of a circular array to 0. In each operation, reduce the current element by 1 (starting from the first element) and move to the next element. Examples: Input: arr[] = {2
    6 min read
  • Minimize increments or decrements required to make sum and product of array elements non-zero
    Given an array arr[] of N integers, the task is to count the minimum number of increment or decrement operations required on the array such that the sum and product of all the elements of the array arr[] are non-zero. Examples: Input: arr[] = {-1, -1, 0, 0}Output: 2Explanation: Perform the following
    6 min read
  • Minimum array elements required to be subtracted from either end to reduce K to 0
    Given an array arr[] consisting of N integers and an integer K, the task is to reduce K to 0 by removing an array element from either end of the array and subtracting it from K. If it is impossible to reduce K to 0, then print "-1". Otherwise, print the minimum number of such operations required. Ex
    9 min read
  • Minimum Subarray flips required to convert all elements of a Binary Array to K
    The problem statement is asking for the minimum number of operations required to convert all the elements of a given binary array arr[] to a specified value K, where K can be either 0 or 1. The operations can be performed on any index X of the array, and the operation is to flip all the elements of
    8 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
  • 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
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