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 number of increment/decrement operations such that array contains all elements from 1 to N
Next article icon

Minimum increment/decrement operations required on Array to satisfy given conditions

Last Updated : 23 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N, the task is to find the minimum number of increment or decrement operations required at any index i such that for each i (1 ? i < N) if the sum of elements at index from 1 to i is positive then the sum of elements from 1 to i + 1 must be negative or vice versa.

Note: Consider array as 1-based indexing.

Examples:

Input: arr[] = {3, -4, 5, 0, 1}
Output: 6
Explanation: 
Convert the array as {3, -4, 5, -5, 2}. Here, the sum of elements till i is represented as si.
For i = 1, s1 = 3 and s2 = 3 + (-4) = -1. s1 is positive and s2 is negative.
For i=2, s2 = -1 and s3 = 3 + (-4) + 5 = 4. s2 is negative and s3 is positive.
For i = 3, s3 = 4 and s4 = 3 + (-4) + 5 + (-5) = -1. s3 is positive and s4 is negative.
For i = 4, s4 = -1 and s5 = 3 + (-4) + 5 +(-5) + 2 = 1. s4 is negative and s5 is positive.

Input: arr[] = {1, -2, 2, -3}
Output: 0
Explanation: 
Given array already satisfies the condition. Therefore, no need to perform any operation. 

Approach: The array will satisfy the conditions if for each i from 1 to N – 1:

  • If i is odd, then the sum of elements from 1 to i is positive.
  • If i is even, then the sum of elements from 1 to i is negative and vice versa.

Try both the above possibilities and choose the one which gives the minimum number of operations. Below are the steps:

  1. Initialize a variable num_of_ops = 0 which marks the number of operations done so far.
  2. For any index i, if i is even and the sum of elements from 1 to i is negative, then add (1+|sum|) in the arr[i] to make it positive. Now the sum of elements from 1 to i will be 1. Also add (1+|sum|) in the num_of_ops i.e., to count the number of operations.
  3. If i is odd and the sum of elements from 1 to i is positive,  then subtract (1+|sum|) from a[i] to make it negative. Now the sum of elements from 1 to i  will be -1. Also add (1+|sum|) in the num_of_ops. i.e., to count the number of operations.
  4. Similarly, find the number of operations taking for even i, the sum of elements till i is negative and for odd i sum of elements till i is positive.
  5. Choose the minimum number of operations from the above two procedures.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <iostream>
using namespace std;
 
// Function to find minimum number
// of operations to get desired array
int minOperations(int a[], int N)
{
    int num_of_ops1, num_of_ops2, sum;
    num_of_ops1 = num_of_ops2 = sum = 0;
 
    // For even 'i', sum of
    // elements till 'i' is negative
 
    // For odd 'i', sum of
    // elements till 'i' is positive
    for (int i = 0; i < N; i++) {
        sum += a[i];
 
        // If i is even and sum is positive,
        // make it negative by subtracting
        // 1 + |s| from a[i]
        if (i % 2 == 0 && sum >= 0) {
            num_of_ops1 += (1 + abs(sum));
            sum = -1;
        }
 
        // If i is odd and sum is negative,
        // make it positive by
        // adding 1 + |s| into a[i]
        else if (i % 2 == 1 && sum <= 0) {
            num_of_ops1 += (1 + abs(sum));
            sum = 1;
        }
    }
 
    sum = 0;
 
    // For even 'i', the sum of
    // elements till 'i' is positive
 
    // For odd 'i', sum of
    // elements till 'i' is negative
    for (int i = 0; i < N; i++) {
        sum += a[i];
 
        // Check if 'i' is odd and sum is
        // positive, make it negative by
        // subtracting  1 + |s| from a[i]
        if (i % 2 == 1 && sum >= 0) {
            num_of_ops2 += (1 + abs(sum));
            sum = -1;
        }
 
        // Check if 'i' is even and sum
        // is negative, make it positive
        // by adding 1 + |s| into a[i]
        else if (i % 2 == 0 && sum <= 0) {
            num_of_ops2 += (1 + abs(sum));
            sum = 1;
        }
    }
 
    // Return the minimum of the two
    return min(num_of_ops1, num_of_ops2);
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 3, -4, 5, 0, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << minOperations(arr, N);
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
class GFG{
 
// Function to find minimum number
// of operations to get desired array
static int minOperations(int a[], int N)
{
    int num_of_ops1, num_of_ops2, sum;
    num_of_ops1 = num_of_ops2 = sum = 0;
 
    // For even 'i', sum of
    // elements till 'i' is negative
 
    // For odd 'i', sum of
    // elements till 'i' is positive
    for (int i = 0; i < N; i++)
    {
        sum += a[i];
 
        // If i is even and sum is positive,
        // make it negative by subtracting
        // 1 + |s| from a[i]
        if (i % 2 == 0 && sum >= 0)
        {
            num_of_ops1 += (1 + Math.abs(sum));
            sum = -1;
        }
 
        // If i is odd and sum is negative,
        // make it positive by
        // adding 1 + |s| into a[i]
        else if (i % 2 == 1 && sum <= 0)
        {
            num_of_ops1 += (1 + Math.abs(sum));
            sum = 1;
        }
    }
 
    sum = 0;
 
    // For even 'i', the sum of
    // elements till 'i' is positive
 
    // For odd 'i', sum of
    // elements till 'i' is negative
    for (int i = 0; i < N; i++)
    {
        sum += a[i];
 
        // Check if 'i' is odd and sum is
        // positive, make it negative by
        // subtracting  1 + |s| from a[i]
        if (i % 2 == 1 && sum >= 0)
        {
            num_of_ops2 += (1 + Math.abs(sum));
            sum = -1;
        }
 
        // Check if 'i' is even and sum
        // is negative, make it positive
        // by adding 1 + |s| into a[i]
        else if (i % 2 == 0 && sum <= 0)
        {
            num_of_ops2 += (1 + Math.abs(sum));
            sum = 1;
        }
    }
 
    // Return the minimum of the two
    return Math.min(num_of_ops1, num_of_ops2);
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array arr[]
    int arr[] = { 3, -4, 5, 0, 1 };
    int N = arr.length;
 
    // Function Call
    System.out.print(minOperations(arr, N));
}
}
 
// This code is contributed by Amit Katiyar
 
 

Python3




# Python3 program for the above approach
 
# Function to find minimum number
# of operations to get desired array
def minOperations(a, N):
 
    num_of_ops1 = num_of_ops2 = sum = 0;
 
    # For even 'i', sum of
    # elements till 'i' is negative
 
    # For odd 'i', sum of
    # elements till 'i' is positive
    for i in range(N):
        sum += a[i]
 
        # If i is even and sum is positive,
        # make it negative by subtracting
        # 1 + |s| from a[i]
        if (i % 2 == 0 and sum >= 0):
            num_of_ops1 += (1 + abs(sum))
            sum = -1
 
        # If i is odd and sum is negative,
        # make it positive by
        # adding 1 + |s| into a[i]
        elif (i % 2 == 1 and sum <= 0):
            num_of_ops1 += (1 + abs(sum))
            sum = 1
 
    sum = 0
 
    # For even 'i', the sum of
    # elements till 'i' is positive
 
    # For odd 'i', sum of
    # elements till 'i' is negative
    for i in range (N):
        sum += a[i]
 
        # Check if 'i' is odd and sum is
        # positive, make it negative by
        # subtracting 1 + |s| from a[i]
        if (i % 2 == 1 and sum >= 0):
            num_of_ops2 += (1 + abs(sum))
            sum = -1
 
        # Check if 'i' is even and sum
        # is negative, make it positive
        # by adding 1 + |s| into a[i]
        elif (i % 2 == 0 and sum <= 0):
            num_of_ops2 += (1 + abs(sum))
            sum = 1
 
    # Return the minimum of the two
    return min(num_of_ops1, num_of_ops2)
 
# Driver Code
if __name__ == "__main__":
     
    # Given array arr[]
    arr = [ 3, -4, 5, 0, 1 ]
    N = len(arr)
 
    # Function call
    print(minOperations(arr, N))
 
# This code is contributed by chitranayal
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find minimum number
// of operations to get desired array
static int minOperations(int []a, int N)
{
    int num_of_ops1, num_of_ops2, sum;
    num_of_ops1 = num_of_ops2 = sum = 0;
 
    // For even 'i', sum of
    // elements till 'i' is negative
 
    // For odd 'i', sum of
    // elements till 'i' is positive
    for(int i = 0; i < N; i++)
    {
        sum += a[i];
 
        // If i is even and sum is positive,
        // make it negative by subtracting
        // 1 + |s| from a[i]
        if (i % 2 == 0 && sum >= 0)
        {
            num_of_ops1 += (1 + Math.Abs(sum));
            sum = -1;
        }
 
        // If i is odd and sum is negative,
        // make it positive by
        // adding 1 + |s| into a[i]
        else if (i % 2 == 1 && sum <= 0)
        {
            num_of_ops1 += (1 + Math.Abs(sum));
            sum = 1;
        }
    }
 
    sum = 0;
 
    // For even 'i', the sum of
    // elements till 'i' is positive
 
    // For odd 'i', sum of
    // elements till 'i' is negative
    for(int i = 0; i < N; i++)
    {
        sum += a[i];
 
        // Check if 'i' is odd and sum is
        // positive, make it negative by
        // subtracting 1 + |s| from a[i]
        if (i % 2 == 1 && sum >= 0)
        {
            num_of_ops2 += (1 + Math.Abs(sum));
            sum = -1;
        }
 
        // Check if 'i' is even and sum
        // is negative, make it positive
        // by adding 1 + |s| into a[i]
        else if (i % 2 == 0 && sum <= 0)
        {
            num_of_ops2 += (1 + Math.Abs(sum));
            sum = 1;
        }
    }
 
    // Return the minimum of the two
    return Math.Min(num_of_ops1, num_of_ops2);
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 3, -4, 5, 0, 1 };
    int N = arr.Length;
 
    // Function call
    Console.Write(minOperations(arr, N));
}
}
 
// This code is contributed by PrinciRaj1992
 
 

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to find minimum number
// of operations to get desired array
function minOperations(a, N)
{
    var num_of_ops1, num_of_ops2, sum;
    num_of_ops1 = num_of_ops2 = sum = 0;
 
    // For even 'i', sum of
    // elements till 'i' is negative
 
    // For odd 'i', sum of
    // elements till 'i' is positive
    for(i = 0; i < N; i++)
    {
        sum += a[i];
 
        // If i is even and sum is positive,
        // make it negative by subtracting
        // 1 + |s| from a[i]
        if (i % 2 == 0 && sum >= 0)
        {
            num_of_ops1 += (1 + Math.abs(sum));
            sum = -1;
        }
 
        // If i is odd and sum is negative,
        // make it positive by
        // adding 1 + |s| into a[i]
        else if (i % 2 == 1 && sum <= 0)
        {
            num_of_ops1 += (1 + Math.abs(sum));
            sum = 1;
        }
    }
 
    sum = 0;
 
    // For even 'i', the sum of
    // elements till 'i' is positive
 
    // For odd 'i', sum of
    // elements till 'i' is negative
    for(i = 0; i < N; i++)
    {
        sum += a[i];
 
        // Check if 'i' is odd and sum is
        // positive, make it negative by
        // subtracting 1 + |s| from a[i]
        if (i % 2 == 1 && sum >= 0)
        {
            num_of_ops2 += (1 + Math.abs(sum));
            sum = -1;
        }
 
        // Check if 'i' is even and sum
        // is negative, make it positive
        // by adding 1 + |s| into a[i]
        else if (i % 2 == 0 && sum <= 0)
        {
            num_of_ops2 += (1 + Math.abs(sum));
            sum = 1;
        }
    }
 
    // Return the minimum of the two
    return Math.min(num_of_ops1, num_of_ops2);
}
 
// Driver Code
 
// Given array arr
var arr = [ 3, -4, 5, 0, 1 ];
var N = arr.length;
 
// Function Call
document.write(minOperations(arr, N));
 
// This code is contributed by aashish1995
 
</script>
 
 
Output: 
6

 

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



Next Article
Minimum number of increment/decrement operations such that array contains all elements from 1 to N

S

sri_srajit
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Mathematical
  • Algorithms-Greedy Algorithms
  • Greedy Algorithms
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical

Similar Reads

  • Minimum increment or decrement operations required to make the array sorted
    Given an array arr[] of N integers, the task is to sort the array in non-decreasing order by performing the minimum number of operations. In a single operation, an element of the array can either be incremented or decremented by 1. Print the minimum number of operations required.Examples: Input: arr
    15+ min read
  • Minimum operations of given type required to empty given array
    Given an array arr[] of size N, the task is to find the total count of operations required to remove all the array elements such that if the first element of the array is the smallest element, then remove that element, otherwise move the first element to the end of the array. Examples: Input: A[] =
    14 min read
  • Count of suffix increment/decrement operations to construct a given array
    Given an array of non-negative integers. We need to construct given array from an array of all zeros. We are allowed to do following operation. Choose any index of say i and add 1 to all the elements or subtract 1 from all the elements from index i to last index. We basically increase/decrease a suf
    5 min read
  • Minimum count of increment of K size subarrays required to form a given Array
    Given an array arr[] and an integer K, the task is to find the minimum number of operations required to change an array B of size N containing all zeros such that every element of B is greater than or equal to arr. i.e., arr[i] >= B[i]. In any operation, you can choose a subarray of B of size K a
    8 min read
  • Minimum number of increment/decrement operations such that array contains all elements from 1 to N
    Given an array of N elements, the task is to convert it into a permutation (Each number from 1 to N occurs exactly once) by using the following operations a minimum number of times: Increment any number.Decrement any number. Examples: Input: arr[] = {1, 1, 4} Output: 2 The array can be converted int
    4 min read
  • Minimize increment or decrement operations to make given Array elements consecutive
    Given an array, arr[] of size N., The task is to perform minimum increment or decrement operations on the elements of the array, to make all the elements consecutive, Output the minimum sum of all the possible changes(addition and subtractions) required to do the same. Examples: Input: N = 5, arr[]
    5 min read
  • Find the minimum operations required to make Array elements Divisible by 3
    mathGiven an array A[] of size N, count the minimum number of operations required such that all the elements of the array are divisible by 3. In one operation, we can take any two elements from the array, remove them, and append their sum at the end of the array. Note: If we can't make all elements
    6 min read
  • Count of decrement operations required to obtain K in N steps
    Given two integers N and K, denoting the number of operations allowed and the number that needs to be obtained after performing N operations respectively. Consider a value S, initially 0, the task is to convert S to K by performing the following operations N times in any manner: Subtract 1 from S.Ad
    9 min read
  • Count minimum decrement prefix or suffix or increment all operations to make Array equal to 0
    Given an array arr[] of size N. The task is to make all the array elements equal to zero by applying the minimum number of operations. Following operations are allowed: Select an index i and decrease each element by 1 for the prefix up to that index.Select an index i and decrease each element by 1 f
    7 min read
  • Minimum increments or decrements required to signs of prefix sum array elements alternating
    Given an array arr[] of N integers, the task is to find the minimum number of increments/decrements of array elements by 1 to make the sign of prefix sum of array alternating. Examples: Input: arr[] = {1, -3, 1, 0}Output: 4Explanation:Following are the operations performed on the given array element
    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