Skip to content

Latest commit

 

History

History
43 lines (37 loc) · 838 Bytes

396.旋转函数.md

File metadata and controls

43 lines (37 loc) · 838 Bytes

396.旋转函数

/*
 * @lc app=leetcode.cn id=396 lang=typescript
 *
 * [396] 旋转函数
 */

// @lc code=start
function maxRotateFunction(nums: number[]): number {}
// @lc code=end

解法 1: 前缀和

function maxRotateFunction(nums: number[]): number {
  let sum1: number[] = [],
    sum = 0,
    n = nums.length
  for (let i = 0; i < n; i++) {
    sum1[i] = (sum1[i - 1] ?? 0) + nums[i]
    sum += nums[i] * i
  }
  let res = -Infinity
  for (let i = 0; i < n; i++) {
    res = Math.max(res, sum + n * sum1[n - i - 1] - (n - i) * sum1[n - 1])
  }
  return res
}

Case

test.each([
  { input: { nums: [4, 3, 2, 6] }, output: 26 },
  { input: { nums: [100] }, output: 0 },
])('input: nums = $input.nums', ({ input: { nums }, output }) => {
  1expect(maxRotateFunction(nums)).toEqual(output)
})