Skip to content

Instantly share code, notes, and snippets.

@shubham1710
Created December 12, 2019 12:20
Show Gist options
  • Save shubham1710/d6db16fe17c14b4d49a5adcf13dd885d to your computer and use it in GitHub Desktop.
Save shubham1710/d6db16fe17c14b4d49a5adcf13dd885d to your computer and use it in GitHub Desktop.
Tyhh
#include<bits/stdc++.h>
using namespace std;
int maxSum(int arr[], int n)
{
// Compute sum of all array elements
int cum_sum = 0;
for (int i=0; i<n; i++)
cum_sum += arr[i];
// Compute sum of i*arr[i] for initial
// configuration.
int curr_val = 0;
for (int i=0; i<n; i++)
curr_val += i*arr[i];
// Initialize result
int res = curr_val;
// Compute values for other iterations
for (int i=1; i<n; i++)
{
// Compute next value using previous
// value in O(1) time
int next_val = curr_val - (cum_sum - arr[i-1])
+ arr[i-1] * (n-1);
// Update current value
curr_val = next_val;
// Update result if required
res = max(res, next_val);
}
return res;
}
// Driver code
int main()
{
int n;
cin>>n;
int arr[n];
for(int u=0;u<n;u++)
cin>>arr[u];
cout << maxSum(arr, n) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment