Thursday, July 7, 2022
HomeWordPress DevelopmentDiscover Worth after performing Increment Decrement queries

Discover Worth after performing Increment Decrement queries


View Dialogue

Enhance Article

Save Article

Like Article

Given a variable X having an preliminary worth 0 and an array of queries Q[] of measurement N containing the kind of operations, the duty is to return the worth of N after performing all of the under operations:

  • Sort-1: Increment the worth of X by 1.
  • Sort-2: Decrement the worth of X by 1. 

Examples: 

Enter: Q = {2, 1, 1}
Output: 1
Clarification: The operations are carried out as observe:
Initially, X = 0,
Question 1(Sort 2): X is decremented by 1, X =  0 – 1 = -1 
Question 2(Sort 1): X is incremented by 1, X = -1 + 1 = 0
Question 3(Sort 1): X is incremented by 1, X = 0 + 1 = 1
Therefore, the output will probably be 1

Enter: Q = {1, 1, 1}
Output: 3

 

Method: To resolve the issue observe the under concept: 

  • Traverse the given array of Queries. 
  • Every time the array aspect is 1, increment N by 1, and 
  • Every time the array aspect is 2, decrement N by 1.
  • Return the ultimate worth of N because the required reply.

Beneath is the implementation for the above method:

C++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

int findvalue(vector<int>& queries)

{

    

    int n = queries.measurement();

    int x = 0;

    for (int i = 0; i < n; i++) {

  

        

        if (queries[i] == 1) {

            x = x + 1;

        }

  

        

        else {

            x = x - 1;

        }

    }

    return x;

}

  

int essential()

{

    

    

    vector<int> queries = { 2, 1, 1 };

    int ans = findvalue(queries);

  

    

    cout << ans;

    return 0;

}

Time Complexity: O(N). 
Auxiliary House: O(1). 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments