K for the Price of One (Hard Version) (Codeforces 1282B2)
Tags: Greedy, sortings

This is the hard version of this problem. The only difference is the constraint on $$$k$$$ — the number of gifts in the offer. In this version: $$$2 \le k \le n$$$.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "$$$k$$$ of goods for the price of one" is held in store.Using this offer, Vasya can buy exactly $$$k$$$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by $$$a_i$$$ — the number of coins it costs. Initially, Vasya has $$$p$$$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary:  Vasya can buy one good with the index $$$i$$$ if he currently has enough coins (i.e $$$p \ge a_i$$$). After buying this good, the number of Vasya's coins will decrease by $$$a_i$$$, (i.e it becomes $$$p := p - a_i$$$).  Vasya can buy a good with the index $$$i$$$, and also choose exactly $$$k-1$$$ goods, the price of which does not exceed $$$a_i$$$, if he currently has enough coins (i.e $$$p \ge a_i$$$). Thus, he buys all these $$$k$$$ goods, and his number of coins decreases by $$$a_i$$$ (i.e it becomes $$$p := p - a_i$$$). Please note that each good can be bought no more than once.For example, if the store now has $$$n=5$$$ goods worth $$$a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$$$, respectively, $$$k=2$$$, and Vasya has $$$6$$$ coins, then he can buy $$$3$$$ goods. A good with the index $$$1$$$ will be bought by Vasya without using the offer and he will pay $$$2$$$ coins. Goods with the indices $$$2$$$ and $$$3$$$ Vasya will buy using the offer and he will pay $$$4$$$ coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.

Input: The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test.The next lines contain a description of $$$t$$$ test cases. The first line of each test case contains three integers $$$n, p, k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le p \le 2\cdot10^9$$$, $$$2 \le k \le n$$$) — the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them.The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^4$$$) — the prices of goods.It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

Output: For each test case in a separate line print one integer $$$m$$$ — the maximum number of goods that Vasya can buy.


Sample Inputs:
8
5 6 2
2 4 3 5 7
5 11 2
2 4 3 5 7
3 2 3
4 2 6
5 2 3
10 1 3 9 2
2 10000 2
10000 10000
2 9999 2
10000 10000
4 6 4
3 2 3 2
5 5 3
1 2 2 1 2

Sample Outputs:
3
4
1
1
2
0
4
5

Solution (Python):
import sys
input = sys.stdin.readline
for _ in range(int(input())):
    (n, p, k) = map(int, input().split())
    a = sorted(list(map(int, input().split())))
    if sum(a) <= p:
        print(n)
    elif a[0] > p:
        print('0')
    else:
        ans = 0
        sm = 0
        for i in range(k + 1):
            s = sm
            if s > p:
                break
            pt = i
            for j in range(i + k - 1, n, k):
                if s + a[j] <= p:
                    pt += k
                    s += a[j]
                else:
                    break
            sm += a[i]
            ans = max(ans, pt)
        print(ans)

Solution (Python):
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(10 ** 7)
input = stdin.readline

def ii():
    return int(input())

def lii():
    return list(map(int, stdin.readline().split()))

def ss():
    x = stdin.readline()
    if x and x[-1] == '\n':
        return x[:-1]
    return x

def lss():
    return list(map(str, stdin.readline().split()))

def llss():
    return [i for i in ss()]

def mpi():
    return map(int, input().split())

def yes(flag):
    if flag:
        stdout.write('YES\n')
    else:
        stdout.write('NO\n')

def pl(lst):
    stdout.write(' '.join(map(str, lst)) + '\n')

def ps(n):
    stdout.write(str(n) + '\n')
from collections import defaultdict, deque
for _ in range(int(input())):
    (n, p, k) = mpi()
    a = lii()
    a.sort()
    start = k - 1
    curr = 0
    res = 0
    ans = 0
    while start < n:
        curr += a[start]
        if curr <= p:
            ans = start + 1
        start += k
    temp = 0
    for i in range(k):
        start = i
        curr = temp
        while start < n:
            curr += a[start]
            if curr <= p:
                ans = max(ans, start + 1)
            start += k
        temp += a[i]
    print(ans)

Solution (Python):
import sys
t = int(sys.stdin.readline().rstrip())

def main():
    for _ in range(t):
        (n, p, k) = map(int, sys.stdin.readline().split())
        (*a,) = map(int, sys.stdin.readline().split())
        a.sort()
        cnt = 0
        cost = 0
        for i in range(k - 1, n, k):
            if cost + a[i] <= p:
                cost += a[i]
                cnt += k
            else:
                r = i - k
                break
        else:
            r = k * (n // k) - 1
        j = 0
        tmp_cost = 0
        while r + j < n - 1:
            j += 1
            cost = sum(a[k - 1 + j:r + j + 1:k]) + tmp_cost
            if cost > p:
                yield cnt
                break
            if cost + a[j - 1] <= p:
                tmp_cost += a[j - 1]
                cnt += 1
            else:
                yield cnt
                break
        else:
            yield n
if __name__ == '__main__':
    ans = main()
    print(*ans, sep='\n')