MAXSTACK Editorial

PROBLEM LINK:

Practice

Author: Prathamesh Sogale
Author: Prathamesh Sogale
Editorialist: Yogesh Deolalkar

DIFFICULTY:

Simple.

PREREQUISITES:

Math

PROBLEM:

Aditya is good at making posters so he participated at poster making contest at his college. His poster stood out among the rest because it was different and appealing, So he easily won the competition. Prices for this competition were unique, and as a winner he was given a chance to select KK prices of his choice .So he was given list of prices, but there is one problem he can only select consecutive prices. Aditya is clever and decided to make most of it. You are given an array of N integers denoting value of each price and you need to select K consecutive prices such that the total value he gets is maximum.

SOLUTIONS:

Setter's Solution

#include<bits/stdc++.h>
using namespace std;
int main() {
int T;
cin>>T;
while(T–) {
long int N,K;
cin>>N>>K;
long int sum=0;
long int arr[N];
for(int i=0;i<N;i++) {
cin>>arr[i];
}
for(int i=0;i<K;i++) {
sum+=arr[i];
}

long int max_sum=sum;
for(int i=K;i<N;i++) {
    max_sum+=arr[i]-arr[i-K];
    sum=max(sum,max_sum);
}
cout<<sum<<endl;
}

}

Tester's Solution

#include
using namespace std;

int main() {
// your code goes here
int t;
cin>>t;
while(t–){
int n,k;
cin>>n>>k;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}

    int sum = 0;
    int maxsum = 0;
    for(int i=0;i<k;i++){
        sum += a[i];
    }
    maxsum = max(sum,maxsum);
    
    for(int i=k;i<n;i++){
        sum = sum + a[i] - a[i-k];
        maxsum = max(sum,maxsum);
    }
    cout<<maxsum<<endl;
}
return 0;

}