Increasing Pair
Increasing Pair
Time limit: 1000 ms
Memory limit: 128 MB
Memory limit: 128 MB
You are given an array A of length N representing a permutation. Find two indices ii and jj such that:
- i<j
- A_i < A_j
- j - i is maximized
Standard input
The first line contains a single integer N.
The second line contains N integers representing the permutation.
Standard output
If there is no solution print -1−1.
Otherwise, output a single integer representing the maximum difference j-i between a valid pair of indices.
Constraints and notes
- 2<=N<=10^5
Simple Input:
4 1 3 4 2
Simple Ouput:
3
题意:给你一个有N个元素的数组,元素是1-N的一个排列,问是否存在一组i,j(i<j)使得a[i]<a[j]并且j-i的值最大
做法:首先用一个pos数组记录下每个元素的位置,然后从N-1扫描,用mx记录下当前位置最大的元素的位置(因为后面的元素都不会比现在的元素大),遇到更大的位置,就更新mx的值,否则就更新maximum
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <algorithm> 5 using namespace std; 6 const int maxN=100005; 7 int pos[maxN]; 8 int main() 9 { 10 int n; 11 while(~scanf("%d",&n)) 12 { 13 int a; 14 for(int i=1;i<=n;i++) 15 { 16 scanf("%d",&a); 17 pos[a]=i; 18 } 19 int mx=0,ans=0; 20 for(int i=n;i>0;i--) 21 { 22 if(pos[i]>mx)mx=pos[i]; 23 else ans=max(ans,mx-pos[i]); 24 } 25 if(ans==0)printf("-1\n"); 26 else printf("%d\n",ans); 27 } 28 return 0; 29 }