• + 0 comments

    When you need to sort the data but keep track of the original index positions, use a pair-index structure. In the code below, the 'quickSort()` routine sorts by price in non-increasing order and for elements that have have the same price, it sorts by index in increasing order.

    typedef struct {
        long long price;
        int index;
    } Pair;
    
    void quickSort(void **a, int lo, int hi);
    
    int minimumLoss(long long* price, int n) {
        long long minLoss = 1e16;
        Pair *pair[n], p[n];
        for (int i = 0; i < n; ++i) {
            pair[i] = &p[i];
            p[i].price = price[i];
            p[i].index = i;
        }
        quickSort((void**) pair, 0, n-1);
        for (int i = 0; i < n-1; ++i) {
            if (pair[i]->index > pair[i+1]->index) continue;
            long long loss = pair[i]->price - pair[i+1]->price;
            if (loss < minLoss) minLoss = loss;
        }
        return minLoss;
    }