当前位置:网站首页>Leetcode0396. 旋转函数(medium,迭代)
Leetcode0396. 旋转函数(medium,迭代)
2022-04-22 08:02:00 【笨牛慢耕】
目录
1. 问题描述
给定一个长度为 n 的整数数组 nums 。
假设 arrk 是数组 nums 顺时针旋转 k 个位置后的数组,我们定义 nums 的 旋转函数 F 为:
F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1]
返回 F(0), F(1), ..., F(n-1)中的最大值 。
生成的测试用例让答案符合 32 位 整数。
示例 1:
输入: nums = [4,3,2,6] 输出: 26 解释: 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 所以 F(0), F(1), F(2), F(3) 中的最大值是 F(3) = 26 。
示例 2:
输入: nums = [100] 输出: 0
提示:
n == nums.length1 <= n <= 10^5-100 <= nums[i] <= 100
2. 解题分析
暴力枚举当然可以得到答案。但是,不应该满足于此。
但是,考虑到旋转的特性,我们可以得到如下递推关系:

More generally,
3. 代码实现
from typing import List
class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
if len(nums)==1:
return 0
# Calculate F(0) and sum of nums
nums_sum = 0
F = 0
N = len(nums)
for k in range(N):
nums_sum += nums[k]
F += k*nums[k]
maxvalue = F
for k in range(1,N):
print(k,F)
F = nums_sum + F - N * nums[(N-k)%N]
maxvalue = F if F> maxvalue else maxvalue
return maxvalue
if __name__ == "__main__":
sln = Solution()
nums = [4,3,2,6]
print(sln.maxRotateFunction(nums))
执行用时:264 ms, 在所有 Python3 提交中击败了89.73%的用户
内存消耗:22 MB, 在所有 Python3 提交中击败了61.98%的用户
版权声明
本文为[笨牛慢耕]所创,转载请带上原文链接,感谢
https://chenxiaoyuan.blog.csdn.net/article/details/124336055
边栏推荐
- winkawaks1. 45 how do I go online? winkawaks1. 45 how to play online (similar to other versions)
- Reorganize notes: [Ultimate method] create user-defined code templates in vscade
- 如何清空输入缓冲区
- PCIe learning - Introduction to PCIe bus architecture: transaction layer - data link layer - physical layer (8)
- 常用的转义字符
- SQL窗口函数
- Putty configuration - feel comfortable
- 一棵开始成长的树
- nacos源代码编译中遇到的问题解决后整理如下
- 实现“ 字体逐渐展现 ”程序
猜你喜欢
随机推荐
CPU memory access space
Tar source package management - source package installation method
ZAB协议
@ data annotation in idea, get / set method does not work
什么产品都还没有 马斯克的“无聊公司”估值已高达57亿美元
规划代码ros移植-POMDP预测规划(一)
elastic-job安装部署接入
How to decrypt the mobile phone number of wechat applet
Solve the problem that the disk has space but cannot create files --- repair the server file system
RHEL7 逻辑卷管理-笔记
选择排序及优化
微信小程序手机号码如何进行解密
RHEL 用户和组的管理-笔记
winkawaks1.45如何联机?winkawaks1.45怎样联机对战(其他版本类似)
The server is set to start automatically and regularly
RHEL7 配置本地yum源
VS编译器注释风格
Vs compiler annotation style
Linux(CentOS)下安装 PostgreSQL
Elastic job installation deployment access









