Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed(method -1)

Question - 

Given an array, to find the maximum value of sum(i*arr[i]) with only rotations on given array allowed.

Example - 

Input : arr[] = {1,20,2,10} , n=4

Output : 72

Input : arr[] = {10,1,2,3,4,5,6,7,8,9} , n=10

Output : 330


Approach - 

first we calculate sum and then rotate array and then calculate sum and compare both and do this n times.


Implementation - 


#include<iostream>

using namespace std;

void rotatearray(int arr[],int n)

{

    int temp=arr[0];

    for(int i=0;i<n-1;i++)

    arr[i]=arr[i+1];

    arr[n-1]=temp;

}

int sumofelement(int arr[],int n)

{

    int sum=0;

    for(int i=0;i<n;i++)

    sum=sum+(i*arr[i]);

    return sum;

}

int sum(int arr[],int n)

{

    int sum1=0,sum2=0;

    sum1=sumofelement(arr,n);

    for(int i=0;i<n-1;i++){

        rotatearray(arr,n);

        sum2=sumofelement(arr,n);

        if(sum1<sum2)

        sum1=sum2;

    }

    cout<<"Result is : "<<sum1<<endl;

}

int main()

{

    int n;

    cout<<"Enter the no of element : ";cin>>n;

    int arr[n];

    cout<<"Enter elements : "<<endl;

    for(int i=0;i<n;i++)

    cin>>arr[i];

    sum(arr,n);

    return 0;

    

}

Time complixity - O(n*n)



Comments