My issue
exlpain me the approach of this question
My code
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
int N, sum = 0, max = 0;
long long a[300000];
cin >> N;
for(int i = 0; i < N; i++)
{
cin >> a[i];
if(a[i] > max){
max = a[i];
}
}
for (int i = 0; i < N; i++)
{
if(a[i] == max)
{
sum = sum + (2*max);
break;
}
else{
sum = sum + a[i];
}
}
cout<<sum<<endl;
}
}
Problem Link: Sale Practice Coding Problem - CodeChef
You are assuming that the day of max sales is the best day to break down the sales. I’ll say this counter example:
A = [1,1,1]
max is 1
Then, when you get into the loop,
i = 0
A[i] = 1
A[i] == max
sum = 0 + 2*1
break
cout << 2 << endl
But that is not true. The max amount of sales is 4, because you can close the last day, which would be 1+1+2
You don’t know what day is the best to close the store, so just try each day like this:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
long long N, sum = 0, maxSales = 0; // Modified
//long long a[300000];
cin >> N;
vector<long long> a(N); // Added
for(int i = 0; i < N; i++)
{
cin >> a[i];
//if(a[i] > max){
// max = a[i];
//}
}
long long prevDays = 0; // Added
for (int i = 0; i < N; i++)
{
maxSales = max(maxSales, prevDays + a[i]*2); // Added
prevDays += a[i]; // Added
}
cout << maxSales << endl; // Modified
}
}