Solve and get sweets

Can anyone tell me what is the logic to solve this question?
my code is here…

#include
#include
#include
#include <bits/stdc++.h>
#define ll long long
#define mod 1000000007;
#define endl “\n” // for fast input,output file
using namespace std;

int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); // these 3 lines for fast I/P method
cout.tie(NULL);
int t;
cin>>t;
while(t–){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++) cin>>arr[i];

    int temp[n];
    for(int i=0;i<n;i++) temp[i]=-arr[i];
    
    int start=0,end=0,s=0,sum=0,res=INT_MIN;
    for(int i=0;i<n;i++){
        sum+=temp[i];
        if(res<sum){
            res=sum;
            start=s;
            end=i;
        }
        if(sum<0){
            sum=0;
            s=i+1;
        }
    }
    int len=end-start+1;
    sum=0;
    for(int i=0;i<n;i++){
        if(i>=start&&i<=end){
            arr[i]=arr[i]+1;
            arr[i]=-arr[i];
        }
        sum+=arr[i];
    }
    
    cout<<max(sum+len,sum)<<endl;
    
}
return 0;

}

Hi,

I got AC on this problem (in practice because of judge error during contest).
My solution(Link) is similar to what you did (based on finding the maximum sum subarray in an array, but with a small modification).
I define the benefit obtained by flipping an element A[j] as ~A[j]-A[j]+1. So I sum this quantity over consecutive elements where this quantity remains positive and take the maximum of it. This gives the maximum extra value obtained by flipping a subset. Of course, the answer is the original sum of array + the extra value obtained

I hope it makes sense