Rotate Function问题及解法

问题描述:

Given an array of integers A and let n to be its length.

Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow:

F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1].

Calculate the maximum value of F(0), F(1), ..., F(n-1).

Note:
n is guaranteed to be less than 105.

示例:

A = [4, 3, 2, 6]

F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26

So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.

问题分析:

假设我们数组中有5个值a,b,c,d,e,根据问题描述我么可以求得如下式子

F(0) = (0a) + (1b) + (2c) + (3d) + (4e)
F(1) = (4
a) + (0b) + (1c) + (2d) + (3e)
F(2) = (3a) + (4b) + (0c) + (1d) + (2e) 

F(3) = (2a) + (3b) + (4c) + (0d) + (1e)
F(4) = (1a) + (2b) + (3c) + (4d) + (0e) 


我们发现由F(k)到F(k + 1)的关系

F(k+1) = F(k)  - sum + A[k] * len,sum是数组的和,len是数组的长度。


过程详见代码:

class Solution {
public:
    int maxRotateFunction(vector<int>& A) {
        int n = A.size();
        if (!n) return 0;
		long res = INT_MIN;
		long f = 0;
		for (int k = 0; k < n; k++)
		{
			f = 0;
			for (int j = 0; j < n; j++)
			{
				f += j * A[(n - k + j) % n];
			}
			if (f > res) res = f;
		}
		return res;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值