Task description
A non-empty zero-indexed array A consisting of N integers is given. Apeak is an array element which is larger than its neighbours. More precisely, it is an index P such that 0 < P < N − 1 and A[P − 1] < A[P] > A[P + 1]. For example, the following array A: A[0] = 1 A[1] = 5 A[2] = 3 A[3] = 4 A[4] = 3 A[5] = 4 A[6] = 1 A[7] = 2 A[8] = 3 A[9] = 4 A[10] = 6 A[11] = 2 has exactly four peaks: elements 1, 3, 5 and 10. You are going on a trip to a range of mountains whose relative heights are represented by array A, as shown in a figure below. You have to choose how many flags you should take with you. The goal is to set the maximum number of flags on the peaks, according to certain rules. Flags can only be set on peaks. What's more, if you take K flags, then the distance between any two flags should be greater than or equal to K. The distance between indices P and Q is the absolute value |P − Q|. For example, given the mountain range represented by array A, above, with N = 12, if you take:
You can therefore set a maximum of three flags in this case. Write a function:
that, given a non-empty zero-indexed array A of N integers, returns the maximum number of flags that can be set on the peaks of the array. For example, the following array A: A[0] = 1 A[1] = 5 A[2] = 3 A[3] = 4 A[4] = 3 A[5] = 4 A[6] = 1 A[7] = 2 A[8] = 3 A[9] = 4 A[10] = 6 A[11] = 2 the function should return 3, as explained above. Assume that:
Complexity:
Elements of input arrays can be modified. |
2.建立一个N元容器C,用以存储第i个元素的下一个peak元素下标。若第i个元素本身就是peak,则C[i]=i,否则C[i]=C[i+1],令C[N-1]=-1
3.由题设可知若有k个flag,则每相邻两个flag之间距离要大于等于k,由于首尾元素均不为peak,故k(k-1)+2<=N,可得k<=floor(sqrt(N))+1
故外层循环:i从1到sqrt(N)+1;令pos表示当前元素下标,num表示内层迭代次数也即flag数,内层循环:pos<N,num<i,先找到一个 peak,即令pos=C[pos],若C[pos]不等于-1,说明当前位置之后仍有peak存在,故pos+=i(flag间隔为i),num++,C[pos]等于-1说明当 前位置之后(含当前位置)无peak存在,跳出内层循环。
用res记录多次迭代中num的最大值,则res就是最大可能的flag数
代码:
// you can use includes, for example:
#include
#include
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector
&A) {
// write your code in C++11
int N = A.size();
vector
B(N,0);
int pos = 0;
int num = 0;
int res = 0;
for(int i=1;i
A[i-1])&&(A[i]>A[i+1])) B[i]=1; } vector
C(N,-1); //C[N-1] = -1;//C[N-2] = -1; for(int i=N-2;i>-1;--i) { if(B[i]) C[i] = i; else C[i] = C[i+1]; } for(int i=1;i<=sqrt(N)+1;++i) { pos = 0; num = 0; while(pos