I am trying to solve a problem where I need to find the maximum value of the sum of i*a[i] for all 0 <= i <= n-1, where a[i] is the element at index i in the array. The only allowed operation is to rotate the array (clockwise or counterclockwise) any number of times.
The code works fine for arrays with size up to 3000, but it fails for larger arrays. Out of 1115 test cases, only 1110 pass successfully.I believe the problem might be with how the current sum is being calculated in each iteration, especially for large arrays.
class Solution {
long max_sum(int a[], int n) {
long sum=0;
long sum1=0;
for(int i=0;i<n;i++){
sum=sum+a[i];
sum1=sum1+(a[i]*i);
}
long sumCurr=sum1;
long sumMax=sum1;
for(int i=n-1;i>=0;i--){
sumCurr = sumCurr-(n*a[i])+sum;
sum1=sumCurr;
if(sumCurr>sumMax){
sumMax=sumCurr;
}
}
return sumMax;
}
}
I also tried modifying the loop like this:
for (int i = 1; i < n; i++) {
sumCurr = sumCurr + sum - n * a[n - i];
sum1 = sumCurr;
if (sumCurr > sumMax) {
sumMax = sumCurr;
}
}
Mihir Vijay is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.