Skip to content

Commit 3e145fa

Browse files
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 99.6 MB (52.11%)
1 parent 9751aa6 commit 3e145fa

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

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: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public:
3+
int maxRotateFunction(vector<int>& nums) {
4+
int n = nums.size();
5+
int cur = 0, sum = 0;
6+
for (int i=0; i<n; i++) {
7+
cur += i * nums[i];
8+
sum += nums[i];
9+
}
10+
int ans = cur;
11+
for (int i=1; i<n; i++) {
12+
cur += sum - n * nums[n-i];
13+
ans = max(ans, cur);
14+
}
15+
return ans;
16+
}
17+
};

0 commit comments

Comments
 (0)