Getting TLE in order of O(n^2) I don’t know how to correct it

#include
using namespace std;
int main()
{
int num;
cin >> num;
int arr[num];
for (int i = 0; i < num; i++)
{
cin >> arr[i];
}
int max1 = 0;
int sum = 0;
for (int i = 1; i < num - 1; i++)
{
max1 = max(max1, arr[i - 1]);
if ((arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) || arr[i] < max1)
{
int max2 = 0;
for (int j = i + 1; j < num; j++)
{
max2 = max(max2, arr[j]);
}
int x = min(max2, max1);
if ((x - arr[i])>0)
{
sum += (x - arr[i]);
}
}
}
cout << sum;
}

@pratham.sharma6113 this question can be done in O(n) you have to optimize your logic

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.