Skip to content

Commit 1f7bda0

Browse files
authored
Add Maximum Array Rotation in C++ (#5172)
1 parent e3f827e commit 1f7bda0

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <sstream>
4+
5+
using namespace std;
6+
int main(int argc, char *argv[]) {
7+
// Check if input exists and isn't empty
8+
if (argc < 2 || string(argv[1]).empty()) {
9+
cout << "Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")";
10+
return 1;
11+
}
12+
// Parse input string
13+
vector<int> arr;
14+
string input = argv[1];
15+
stringstream ss(input);
16+
string token;
17+
18+
while (getline(ss, token, ',')) {
19+
arr.push_back(stoi(token));
20+
}
21+
22+
int n = arr.size();
23+
int arr_sum = 0;
24+
int current_sum = 0;
25+
// Get sum of array and first rotation sum
26+
for (int i = 0; i < n; i++) {
27+
arr_sum += arr[i];
28+
current_sum+= i * arr[i];
29+
}
30+
31+
int max_sum = current_sum;
32+
// check all other possible rotations
33+
for (int j = 1; j < n; j++) {
34+
int rotating_value = arr[n-j];
35+
// next sum = current sum + gains of shifting values one index higher - loss of moving highest index to 0
36+
current_sum = current_sum + arr_sum - n * rotating_value;
37+
38+
if (current_sum > max_sum) {
39+
max_sum = current_sum;
40+
}
41+
}
42+
cout << max_sum << endl;
43+
return 0;
44+
}

0 commit comments

Comments
 (0)