Topic source:
Codility
Base Time Limit: 1 second Space Limit: 131072 KB Score: 20Difficulty
: Level 3 Algorithm Questions
collect
focus on
Given an integer array A of length N, for each array element, if there is a number greater than or equal to the element after it, these two numbers can form a pair. Each element and itself can also form a pair. For example: {5, 3, 6, 3, 4, 2}, 11 pairs can be formed as follows (numbers are subscripts):
(0,0), (0, 2), (1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (3, 3), (3 , 4), (4, 4), (5, 5). where (1, 4) is the pair with the largest distance, and the distance is 3.
Input
Line 1: 1 number N, representing the length of the array (2 <= N <= 50000). Lines 2 - N + 1: 1 number per line, corresponding to array element Ai (1 <= Ai <= 10^9).
Output
Output the maximum distance.
Input example
6 5 3 6 3 4 2
Output example
3
Traverse each number ai and find the farthest position on the right that is larger than ai. Sort + Suffix. Sort first, then the ith row is larger than the ith row, and then find the maximum row of the subscript in in.
1 #include <bits/stdc++.h> 2 #define ll long long 3 using namespace std; 4 const int N = 5e4+10; 5 int pre[N], n; 6 struct Nod{ 7 int num,id; 8 }nod[N]; 9 bool cmp(Nod &a, Nod &b) { 10 if(a.num != b.num) return a.num < b.num; 11 else return a.id < b.id; 12 } 13 int main() { 14 cin >> n; 15 for(int i = 1; i <= n; i ++) { 16 cin >> nod[i].num; 17 nod[i].id = i; 18 } 19 sort(nod+1,nod+1+n,cmp); 20 pre[n] = nod[n].id; 21 for(int i = n-1; i > 0; i --) { 22 pre[i] = max(pre[i+1],nod[i].id); 23 } 24 int MAX = 0; 25 for(int i = 1; i < n; i ++) { 26 MAX = max(MAX, pre[i+1]-nod[i].id); 27 } 28 cout << MAX << endl; 29 return 0; 30 }