-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Max_sum_in_the_configuration.cpp
72 lines (62 loc) · 1.38 KB
/
Max_sum_in_the_configuration.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
Description :
Given an array(0-based indexing), you have to find the max sum of i*A[i] where A[i] is the element at index i in the array.
The only operation allowed is to rotate(clock-wise or counter clock-wise) the array any number of times.
*/
#include <bits/stdc++.h>
using namespace std;
// function to find the combination of the number and sum
int maxi_sum(int A[], int N)
{
// c_s = current sum
int c_s = 0;
for (int i = 0; i < N; i++)
{
c_s += A[i];
}
int c_v = 0;
for (int i = 0; i < N; i++)
{
c_v = c_v + i * A[i];
}
int ans = c_v;
for (int i = 1; i < N; i++)
{
int n_v = c_v - (c_s - A[i - 1]) + A[i - 1] * (N - 1);
c_v = n_v;
ans = max(ans, n_v);
}
return ans;
}
int main()
{
// input number
int num;
cout << "Enter the size of array : " << endl;
cin >> num;
// array to store input
int arr[num];
cout << "Enter the elements in the array : " << endl;
for (int i = 0; i < num; i++)
{
cin >> arr[i];
}
cout << "Maximum sum which can be obtained : " << endl;
cout << maxi_sum(arr, num) << endl;
return 0;
}
/*
Time complexity - O(N)
Space complexity - O(1)
*/
/*
Test Case :
Input :
Enter the size of array :
4
Enter the elements in the array :
8 3 1 2
Output :
Maximum sum which can be obtained :
29
*/