samedi 7 mars 2015

Choose the right algorithm


I have this problem:

there is a integer vector of N elements, I call it A.

Then there are two elements, I call them (P,Q), such that 0<= P <= Q <N (P,Q are indexes of A).

We use the two elements to compute L = A[P] + A[Q] + (Q-P).


I have to compute the maximum value of L using an algorithm with complexity O(n) and using O(1) memory.


This is my solution but I think it is O(n^2):



int L = 0;

for(int i=0; i<A.size(); i++) {
for(int j=i; j<A.size(); j++) {
L = max(L, A[i] +A[j] +(j-i) );
}
}

cout<<"Best: "<<L<<endl;


Do you have better algorithms to solve this problem?




Aucun commentaire:

Enregistrer un commentaire