My code is showing the correct output for some test cases. Can anyone tell me what is wrong with my code?
#include<bits/stdc++.h>
using namespace std ;
int main () {
#ifndef ONLINE_JUDGE
freopen(“input.txt” , “r” , stdin);
freopen(“output.txt” , “w” , stdout);
#endif
int n , k ;
cin >> n >> k ;
int a[n] ;
for (int i = 0 ; i < n; i++) {
cin >> a[i];
}
long long dp[10000];
if (a[0] >= 0)
{
dp[0] = a[0];
}
else {
dp[0] = 0 ;
}
for (int i = 1 ; i < k ; i++)
{
if (a[i] > dp[i - 1])
{
dp[i] = a[i] ;
}
else {
dp[i] = dp[i - 1];
}
}
if (k == n)
{
cout << dp[n - 1] << endl;
}
else {
for (int i = 1 ; i < ((n + k - 1 ) / k) ; i++)
{
int start = i * k ;
int max1 = 0 , max2 = 0 , max_index = -1 ;
//find the first and the second maximum in the previous block
for (int l = (i - 1) * k ; l < (i)*k ; l++)
{
if (dp[l] > max1)
{
max2 = max1 ;
max1 = dp[l] ;
max_index = l ;
}
else if (a[l] > max2)
{
max2 = dp[l] ;
}
}
for (int j = start; j < min(((i + 1) * k), n); j++)
{
if (j - k != max_index)
{
if (a[j] >= 0) {
dp[j] = a[j] + max1;
}
else {
dp[j] = max1;
}
}
else {
if (a[j] >= 0) {
dp[j] = a[j] + max2;
}
else {
dp[j] = max2;
}
}
}
}
int s = n / k , res = 0 ;
for (int i = s * k ; i < n ; i++)
{
if (dp[i] > res)
res = dp[i];
}
cout << res << endl;
}
return 0;
}