Skip to the code
+50 XP

#85 Best Rotation Score

hard

A homepage has a row of featured slots, and slot i gets i units of attention (later slots are seen more as the user scrolls). The products' values are in nums. The score of an arrangement is the sum of i * value over all slots.

You may rotate nums right by any k from 0 to n - 1 before placing it. Write bestRotationScore(nums) that returns the highest score any rotation can get. Aim for O(n) time.

Example 1

Input: nums = [1,5,2]
Output: 11

Rotating right by 1 gives [2, 1, 5], scoring 0 * 2 + 1 * 1 + 2 * 5 = 11.

Example 2

Input: nums = [7]
Output: 0

The only slot is slot 0, which scores nothing.

Constraints

  • 1 <= nums.length <= 10^5
  • -100 <= nums[i] <= 100
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).