旋转一个数组以得到最大值。
陷阱就是:不能排序。须要模拟操作旋转,并设计公式计算旋转后的和。
要求是O(n)时间完毕。
原题:
https://www.hackerrank.com/challenges/game-of-rotation
#pragma once#includeclass GameOfRotation{public: GameOfRotation() { int N = 0; scanf("%d", &N); int *A = new int[N]; long long one = 0, sum = 0, ans = 0; for (int i = 0; i < N; i++) { scanf("%d", &A[i]); one += (long long)A[i]; sum += (long long)(i+1) * (long long)A[i]; } ans = sum; for (int i = 1; i < N; i++) { sum = sum - one + (long long)A[i-1] * (long long)N; ans = ans < sum ? sum : ans; } printf("%lld", ans); delete [] A; }};int gameOfRotation(){ GameOfRotation(); return 0;}