How to find the index of second largest element in an array collection?

后端 未结 3 633
攒了一身酷
攒了一身酷 2021-01-25 08:43

I have a function which calculates sum of money spent on each checkout on a counter, After calculation, i want to find the best two checkout counter, I am able to find the index

3条回答
  •  没有蜡笔的小新
    2021-01-25 09:20

    The second best is not sent only when you outperform the best.

    Example with 40, 60, 50, 30

    With your code, the fist time you set a best, is with 40. Then 60 replaces it an 40 becomes the second best. THen 50 arrives but it doesn't outperform the best so gets ignored as second best.

    You have to add an clause, to handle this case:

    ...
    if (sumM > maxmoney)   // as you already did
    {
        Secondbestcheckout=firstbestcheckout;
        firstbestcheckout = indexofmax+1;
        secondmaxmoney = maxmoney;   // < secondmaxmoney)       // NEW STATEMENT  
    {
        Secondbestcheckout= ...;       // as above, but unclear for me what the difference with secondinex is
        secondmaxmoney = maxmoney;     // update amount onf second best
        secondindex = i;               // or i+1 ?  Not clear if you start from 0 or from 1 
    }
    ...  // rest or your code
    

提交回复
热议问题