Maximize the Weighted Sum Over Clockwise Rotations
Quick Overview
Practice maximizing an index-weighted sum over clockwise array rotations. Handle negative values, the final result guarantee, and safe intermediate arithmetic.
Maximize the Weighted Sum Over Clockwise Rotations
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
# Maximize the Weighted Sum Over Clockwise Rotations
Given an integer array `nums` of length `n`, let `arr_k` be the array obtained by rotating it clockwise by `k` positions. Define
```text
F(k) = 0*arr_k[0] + 1*arr_k[1] + ... + (n-1)*arr_k[n-1].
```
Return the maximum of `F(0)` through `F(n-1)`. The returned maximum is guaranteed to fit a signed 32-bit integer.
### Function
`int maxRotateFunction(vector<int>& nums)`
### Example 1
```text
Input: nums = [1,-2,3]
Output: 5
```
| Clockwise rotation | Array | Weighted sum |
| --- | --- | --- |
| `0` | `[1,-2,3]` | `4` |
| `1` | `[3,1,-2]` | `-3` |
| `2` | `[-2,3,1]` | `5` |
### Example 2
```text
Input: nums = [-1,-2]
Output: -1
```
### Example 3
```text
Input: nums = [7]
Output: 0
```
### Constraints
- `1 <= nums.length <= 100000`.
- `-100 <= nums[i] <= 100`.
- The maximum weighted sum over all rotations fits a signed 32-bit integer.
### Clarifications
A clockwise rotation moves the last element to the front for each step. Negative values are allowed, and the maximum may be negative. Return the maximum sum, not the rotation index. The range guarantee is for the returned maximum, not every intermediate calculation.
### What a Strong Answer Covers
- Correct rotation direction and positional weights.
- All-negative arrays and a single element.
- Why every rotation's value is accounted for.
- Correctness, numeric safety, and resource bounds.
Overview: Practice maximizing an index-weighted sum over clockwise array rotations. Handle negative values, the final result guarantee, and safe intermediate arithmetic.
Return the maximum of F(0) through F(n-1). The returned maximum is guaranteed to fit a signed 32-bit integer.
Function
int maxRotateFunction(vector<int>& nums)
Example 1
Input: nums = [1,-2,3]
Output: 5
Clockwise rotation
Array
Weighted sum
0
[1,-2,3]
4
1
[3,1,-2]
-3
2
[-2,3,1]
5
Example 2
Input: nums = [-1,-2]
Output: -1
Example 3
Input: nums = [7]
Output: 0
Constraints
1 <= nums.length <= 100000
.
-100 <= nums[i] <= 100
.
The maximum weighted sum over all rotations fits a signed 32-bit integer.
Clarifications
A clockwise rotation moves the last element to the front for each step. Negative values are allowed, and the maximum may be negative. Return the maximum sum, not the rotation index. The range guarantee is for the returned maximum, not every intermediate calculation.
What a Strong Answer Covers Guidance
Correct rotation direction and positional weights.