- Arrays, frequency-counting, Greedy

Maximize the profit after selling the tickets | Set 2 (For elements in range [1, 10^6])

                                   function maxAmount(n, k, arr)        {                                             let A = new Array(1000001).fill(0);            for (let i = 0; i < n; i++)            {                A[arr[i]]++;            }            let j = 0;                                                 for (let i = 0; i < 1000001; i++) {                while (A[i] != 0) {                    arr[j++] = i;                    A[i]--;                }            }                        let ans = 0;            let mod = 1e9 + 7;            let i = n - 1;            j = n - 2;                                    while (k > 0 && j >= 0) {                                                                if (arr[i] > arr[j]) {                    ans = ans + Math.min(k, (i – j)) * arr[i];                    k = k – (i – j);                    arr[i]–;                }                else {                                                            while (j >= 0 && arr[j] == arr[i])                        j–;                    if (j < 0)                        break;                                        ans = ans + Math.min(k, (i - j)) * arr[i];                    k = k - (i - j);                    arr[i]--;                }            }                                                while (k > 0 && arr[i] != 0) {                ans = ans + Math.min(n, k) * arr[i];                k -= n;                arr[i]–;            }            ans = ans % mod;                                    let x = ans;            return x;        }                        let n = 5;        let k = 3;        let arr = [4, 3, 6, 2, 4];                let ans = maxAmount(n, k, arr);        document.write(ans);