1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <set>
#include <algorithm>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::max;
using std::set;

int main()
{
    int n;
    int k;
    int firstAmount = 0;
    long long int amount = 0;
    cin >> n;
    cin >> k;

    // get data and check if there is enough different bottles
    int sales[n];
    int differentBottles[500001];
    int maxNum = 0;
    for (int i = 0; i < 500001; i++)
    {
        differentBottles[i] = 0;
    }

    int got;
    for (int i = 0; i < n; i++)
    {
        cin >> got;
        sales[i] = got;
        differentBottles[got] = 1;
    }
    for (int i = 0; i < 500001; i++)
    {
        if (differentBottles[i] == 1)
        {
            firstAmount++;
        }
    }

    if (firstAmount < k)
    {
        cout << -1;
    }
    else
    {

        // check bottles from the left
        int lastDiffBottle = 0;
        // int amountOfDiffBottles = 0;

        for (int i = 0; i < k; i++)
        {
            if (differentBottles[sales[i]] == 2)
            {
                if (lastDiffBottle > 0)
                {
                    amount = amount + max((lastDiffBottle - i), (i - lastDiffBottle));
                }

                for (int j = max(i + 1, lastDiffBottle + 1); j < n; j++)
                {
                    amount++;
                    if (differentBottles[sales[j]] != 2)
                    {
                        differentBottles[sales[j]] = 2;
                        lastDiffBottle = j;
                        break;
                    }
                }
            }
            if (differentBottles[sales[i]] == 1)
            {
                differentBottles[sales[i]] = 2;
            }

            // // it is probably nont needed
            // amountOfDiffBottles++;
            // if (amountOfDiffBottles == k)
            // {
            //     break;
            // }
        }

        cout << amount;
    }
}