
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Operations to Reduce a Number in C++
We are given with a positive integer K and an array Ops[] which contains integers. The goal is to find the number of operations required to reduce K such that it becomes less than 0. Operations are −
First operation is K + Ops[0], first element added to K
After 1. Add Ops[i] to K until K<0. where index i keeps on changing in a circular manner. 0<=i<N. N is the number of integers in Ops[].
Note − Keep adding Ops[i] until K<0. If i reaches the last element Ops[N-1] then again start from i=0. In a circular manner.
We will first check if the sum of all elements of array Ops[] >0. If yes then K can never be reduced. Return -1. Otherwise keep adding Ops[i] to K and check if K<0 if yes break the loop.
Increment count of operations after addition: K+Ops[i].
Let’s understand with examples.
Input −
ops[]= { -4,2,-3,0,2 }, K=5
Output − Count of operations required to reduce a number − 3
Explanation − K is 5. Operations are −
1. K+ops[0]= 5+(-4) = 1 2. K+ops[1]= 1+2 = 3 3. K+ops[2]= 3+(-3) = 0
Input −
ops[]= { 5,5,3,-2 }, K=10
Output − K cannot be reduced!!
Explanation −K is 10. Operations are −
1. K+ops[0]= 10+5= 15 2. K+ops[1]= 15+5= 20 3. K+ops[2]= 20+3= 23 4. K+ops[3]= 23+-2= 22 5. K+ops[0]= 22+5= 27 6. K+ops[1]= 27+5=32 7. …………………
If we early check the sum of all elements of ops[]=5+5+3-2=11 and 11+10 is always +ve. So K cannot be reduced to −0.
Approach used in the below program is as follows
We take an integer array ops[] initialized with random integers.
Variable K is given a positive value.
Function countOperations(int op[], int n, int k) takes K array Ops[] and its length as parameters and return operations required to reduce K to less than 0.
Take the initial number of operations as 0 in count.
Calculate sum of elements of ops[] and store in sum. If sum>=0 then return -1.
If not while k>0 keep adding ops[i] and increment count. If k<0 break loop.
Return count as result.
Example
#include <bits/stdc++.h> using namespace std; long countOperations(int op[], int n, int k){ long count = 0; int sum=0; int i=0; for(int i=0;i<n;i++){ sum+=op[i]; } if(sum-k>=0) { return -1; } //number k can never be reduced as sum-k is always positive or 0 while(k>0){ for(i=0;i<n;i++){ if(k>0){ count++; k+=op[i]; } else { break; } } } return count; } int main(){ int Ops[] = { 1,-1,5,-11}; int len= sizeof(Ops) / sizeof(Ops[0]); int K=10; long ans=countOperations(Ops,len,K); if(ans==-1) { cout<<"K cannot be reduced!!"; } else { cout<<"Number of operations : "<<ans; } return 0; }
Output
If we run the above code it will generate the following output −
Number of operations : 8