|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <string.h> |
| 4 | + |
| 5 | +void calculate_maximum_rotation(char *input) { |
| 6 | + // Parse the input string into an array of integers |
| 7 | + int arr[100], n = 0; |
| 8 | + char *token = strtok(input, ","); |
| 9 | + |
| 10 | + while (token != NULL) { |
| 11 | + arr[n++] = atoi(token); |
| 12 | + token = strtok(NULL, ","); |
| 13 | + } |
| 14 | + |
| 15 | + // Edge case: No input or empty input |
| 16 | + if (n == 0) { |
| 17 | + printf("Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")\n"); |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + // Calculate initial weighted sum |
| 22 | + int total_sum = 0, weighted_sum = 0; |
| 23 | + |
| 24 | + for (int i = 0; i < n; i++) { |
| 25 | + weighted_sum += i * arr[i]; |
| 26 | + total_sum += arr[i]; |
| 27 | + } |
| 28 | + |
| 29 | + int max_weighted_sum = weighted_sum; |
| 30 | + |
| 31 | + // Calculate maximum weighted sum after rotations |
| 32 | + for (int i = 1; i < n; i++) { |
| 33 | + weighted_sum = weighted_sum + total_sum - n * arr[n - i]; |
| 34 | + if (weighted_sum > max_weighted_sum) { |
| 35 | + max_weighted_sum = weighted_sum; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + printf("%d\n", max_weighted_sum); |
| 40 | +} |
| 41 | + |
| 42 | +int main(int argc, char *argv[]) { |
| 43 | + if (argc != 2) { |
| 44 | + printf("Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")\n"); |
| 45 | + return 1; |
| 46 | + } |
| 47 | + |
| 48 | + calculate_maximum_rotation(argv[1]); |
| 49 | + return 0; |
| 50 | +} |
0 commit comments