Algorithm for finding the maximum difference in an array of numbers

后端 未结 7 494
夕颜
夕颜 2021-02-04 03:57

I have an array of a few million numbers.

double* const data = new double (3600000);

I need to iterate through the array and find the range (th

7条回答
  •  野的像风
    2021-02-04 04:30

    The algorithm you describe is really O(N), but i think the constant is too high. Another solution which looks reasonable is to use O(N*log(N)) algorithm the following way:

    * create sorted container (std::multiset) of first 1000 numbers
    * in loop (j=1, j<(3600000-1000); ++j)
       - calculate range
       - remove from the set number which is now irrelevant (i.e. in index *j - 1* of the array)
       - add to set new relevant number  (i.e. in index *j+1000-1* of the array)
    

    I believe it should be faster, because the constant is much lower.

提交回复
热议问题