
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Global and Local Inversions in C++
Suppose we have some permutation A of [0, 1, ..., N - 1], where N is the length of A. Now the number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > A[j]. And the number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1]. We have to return true if and only if the number of global inversions is equal to the number of local inversions. So if the input is like [1,0,2], then return true, as there is only one local inversion and one global inversion.
To solve this, we will follow these steps −
- maxVal := -1, n := size of A
- for i in range 0 to n – 3
- maxVal := max of A[i] and maxVal
- if maxVal > A[i + 2], then return false
- return true
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: bool isIdealPermutation(vector<int>& A) { int maxVal = -1; int n = A.size(); for(int i = 0; i < n - 2; i++){ maxVal = max(A[i], maxVal); if(maxVal > A[i + 2]) return false; } return true; } }; main(){ vector<int> v = {1,0,2}; Solution ob; cout << (ob.isIdealPermutation(v)); }
Input
[1,0,2]
Output
1
- Related Articles
- Program to check number of global and local inversions are same or not in Python
- Global and Local Variables in C#
- What are local variables and global variables in C++?
- Global and Local Variables in Python?
- Global and Local Variables in Java
- Difference between static, auto, global and local variable in C++
- Difference Between Local and Global Variable
- What are the local and global scope rules in C language?
- How are C++ Local and Global variables initialized by default?
- Global vs Local variables in Python
- What is the difference between global and local variables in Python?
- What is the difference between global and local Variables in JavaScript?
- What are the rules for local and global variables in Python?
- What is the difference between Local Events and Global Events in jQuery?
- Counting Inversions using Set in C++ STL

Advertisements