Source Code
#include <bits/stdc++.h>
using namespace std;

const int M = 2e5;

int n, A[M], k1, k2, k3, memo[M][4][5][8];

int solve(int i, int a, int b, int c) {
    if (i == n)
        return 0;

    int &res = memo[i][a][b][c];
    if (res == -1) {
        res = solve(i + 1, a, b, c);
        if (abs(A[i] % 4 - a) <= k1 && abs(A[i] % 5 - b) <= k2 && abs(A[i] % 8 - c) <= k3)
            res = max(res, 1 + solve(i + 1, A[i] % 4, A[i] % 5, A[i] % 8));
    }
    return res;
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    memset(memo, -1, sizeof memo);
    cin >> n >> k1 >> k2 >> k3;
    for (int i = 0; i < n; i++)
        cin >> A[i];
    int ans = 0;

    for (int i = 0; i < n; i++)
        ans = max(ans, 1 + solve(i + 1, A[i] % 4, A[i] % 5, A[i] % 8));
    cout << ans << '\n';
}
Copy
Band Song 2 ahmad_salah
GNU G++17
499 ms
142.1 MB
Accepted