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 1Enter: 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++
|
Time Complexity: O(N).Â
Auxiliary House: O(1).Â