 Need help in this code :Jobathon(GFG) Special Array

Given an array m[ ] of npositive numbers.
Find the largest possible sum of elements of a special array ans[ ] that can be generated using the following condition on given array m[ ].

ans[i]<=m[i] for 0<=i<n

A special array is defined as the array which does not hold the following condition:
ans[j]>ans[i]<ans[k] where 0<=j<i<k<n

Example:

N = 5 m[ ] = {1,5,3,5,4}
Output:16
Explanation: The special array will be [1,3,3,5,4] with sum = 16, which is maximum. No other special array can achieve higher sum.

Can someone tell me the right solution for this problem:

This was my solution:

class Solution {
public :
long long specialSum(vector m, int n)
{
if(n<=2)return accumulate(m.begin(), m.end(), 0);

long long sum=m;
for(int i=1;i<n-1;i++)
{
if((m[i]<m[i-1]) and (m[i]<m[i+1]))
{
if(m[i-1]>=m[i+1])
{
// sum-=m[i+1]-m[i];
m[i+1]=m[i];
}
else
{
long long t=m[i-1]-m[i];
sum-=t;

}

}
sum+=m[i];
}
sum+=m[n-1];

return sum;

}

};

I have unlocked the full solution I can send it to you, but can you tell why my solution is wrong. We can make the special array just by using the given array and whenever we face the condition of a[j]>a[i]<a[k] we can just make a[j] = a[i] then we will have the maximum sum. But this solution is wrong but I don’t know why

I know,I can’t figure out what I did wrong either…

class Solution {
public :
long long specialSum(vector m,int N) {
stack<pair<long long ,long long>> st ;
vector pref(N), suff(N) ;
pref = m ;
st.push({m,1LL}) ;
for(int i = 1 ; i < N ; ++i) {
long long cnt =0 ;
pref[i] = pref[i-1] ;
while(st.size() > 0 && st.top().first > m[i]) {
long long val = st.top().first ;
long long c = st.top().second ;
cnt += c ;
pref[i] -= val * c ;
st.pop();
}
st.push({m[i],cnt+1}) ;
pref[i] += (cnt+1)*m[i] ;
}

suff[N-1] = m[N-1] ;
while(st.size())
st.pop();
st.push({m[N-1],1}) ;
for(int i = N-2 ; i >= 0 ; --i) {

long long cnt =0 ;
suff[i] = suff[i+1] ;
while(st.size() > 0 && st.top().first > m[i]) {
long long val = st.top().first ;
long long c = st.top().second ;
cnt += c ;
suff[i] -= val * c ;
st.pop() ;
}
st.push({m[i],cnt+1}) ;
suff[i] += (cnt+1)*m[i] ;
}
long long ans = -1 ;
for(int i = 0 ; i < N ; ++i) {
long long tmp = pref[i] ;
tmp += suff[i];
tmp -= m[i] ;
ans = max(ans, tmp) ;
}
return ans;
}

};