java - Maximum increasing difference -


i need find maximum increasing distance or difference between numbers in vector. example, in vector [10, 5, 20, 45, 5, 5, 7] on first pass looks difference between 10 , 45 maximum. on second iteration difference between 5 , 45 larger, should chosen algorithm.

i have solution o(n^2) , life of me can't figure out if there solution lower computational complexity.

public void maxdistance(int inputarray[]) {     int truemaxvalue = 0,   trueminindex = 0,   truemaxindex = 0,  tempmaxvalue;      (int = 0; < inputarray.length - 1; ++i) {         (int j = + 1; j < inputarray.length; ++j) {             tempmaxvalue = inputarray[j] - inputarray[i];             if (tempmaxvalue > truemaxvalue) {                 truemaxvalue = tempmaxvalue;                 trueminindex = i;                 truemaxindex = j;             }         }     } } 

i need know 2 numbers in array used in max. can please help? don't know if should continue think or o(n^2) best can do?

you can in o(n) stephany. need add few variables remember current best solution. using current naming convention can following:

    public void maxdistance(int inputarray[]) {         int currentmin = inputarray[0],     currentminindex = 0;         int truemaxvalue = 0,   trueminindex = 0,   truemaxindex = 0;         int tempmaxvalue;          int = 1;         while (i < inputarray.length) {             tempmaxvalue = inputarray[i] - inputarray[currentminindex];             if (tempmaxvalue > truemaxvalue) {                 truemaxvalue = tempmaxvalue;                 trueminindex = currentminindex;                 truemaxindex = i;             }              if (inputarray[i] < currentmin) {                 currentminindex = i;                 currentmin = inputarray[i];             }              ++i;         } 

Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -