Algorithm for finding the maximum difference in an array of numbers

后端 未结 7 582
夕颜
夕颜 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:13

    std::multiset range;
    double currentmax = 0.0;
    for (int i = 0;  i < 3600000;  ++i)
    {
        if (i >= 1000)
            range.erase(range.find(data[i-1000]));
        range.insert(data[i]);
        if (i >= 999)
            currentmax = max(currentmax, *range.rbegin());
    }
    

    Note untested code.

    Edit: fixed off-by-one error.

提交回复
热议问题