Skip to content

Commit be0b658

Browse files
committed
[LeetCode Sync] Runtime - 171 ms (67.42%), Memory - 25.7 MB (44.15%)
1 parent c5a2e27 commit be0b658

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p>
2+
3+
<p>Assume <code>arr<sub>k</sub></code> to be an array obtained by rotating <code>nums</code> by <code>k</code> positions clock-wise. We define the <strong>rotation function</strong> <code>F</code> on <code>nums</code> as follow:</p>
4+
5+
<ul>
6+
<li><code>F(k) = 0 * arr<sub>k</sub>[0] + 1 * arr<sub>k</sub>[1] + ... + (n - 1) * arr<sub>k</sub>[n - 1].</code></li>
7+
</ul>
8+
9+
<p>Return <em>the maximum value of</em> <code>F(0), F(1), ..., F(n-1)</code>.</p>
10+
11+
<p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p>
12+
13+
<p>&nbsp;</p>
14+
<p><strong class="example">Example 1:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> nums = [4,3,2,6]
18+
<strong>Output:</strong> 26
19+
<strong>Explanation:</strong>
20+
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
21+
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
22+
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
23+
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
24+
So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
25+
</pre>
26+
27+
<p><strong class="example">Example 2:</strong></p>
28+
29+
<pre>
30+
<strong>Input:</strong> nums = [100]
31+
<strong>Output:</strong> 0
32+
</pre>
33+
34+
<p>&nbsp;</p>
35+
<p><strong>Constraints:</strong></p>
36+
37+
<ul>
38+
<li><code>n == nums.length</code></li>
39+
<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>
40+
<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>
41+
</ul>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def maxRotateFunction(self, nums: List[int]) -> int:
3+
dp = sum(i * val for i, val in enumerate(nums))
4+
n = len(nums)
5+
sum_val = sum(nums)
6+
result = dp
7+
for i in range(1, n):
8+
dp = dp + sum_val - n*nums[n - i]
9+
result = max(result, dp)
10+
11+
return result

0 commit comments

Comments
 (0)