【HackerRank】Game Of Rotation

题目连接:Game Of Rotation

Mark is an undergraduate student and he is interested in rotation. A conveyor belt competition is going on in the town which Mark wants to win. In the competition, there's A conveyor belt which can be represented as a strip of 1xN blocks. Each block has a number written on it. The belt keeps rotating in such a way that after each rotation, each block is shifted to left of it and the first block goes to last position.

There is a switch near the conveyer belt which can stop the belt. Each participant would be given a single chance to stop the belt and his PMEAN would be calculated.

PMEAN is calculated using the sequence which is there on the belt when it stops. The participant having highest PMEAN is the winner. There can be multiple winners.

Mark wants to be among the winners. What PMEAN he should try to get which guarantees him to be the winner.

where i is the index of a block at the conveyor belt when it is stopped. Indexing starts from 1.

Input Format 
First line contains N denoting the number of elements on the belt. 
Second line contains N space separated integers.

Output Format 
Output the required PMEAN

Constraints 
1 ≤ N ≤ 106
-109 ≤ each number ≤ 109


 

题解:一开始非常2b的觉得尽量大的索引值对应大的数组值,于是就把数组排序,然后把索引*值的和求出来。

这个想法最大的bug就是数组只能通过平移变化,不能随意变化,所以排序得到的数组有可能通过变换得不到。

正确的方法就是模拟n次变换,每次把第一个元素放到最后,然后计算新的和。注意从旧的和可以直接得到新的和: new_sum = old_sum - (a1+a2+...+an) + n*a[i]; 其中a[i]是在当前的循环中被放到结尾的数。只有它的索引值增加了(n-1),其他元素的索引值都减少了1。

最后要注意的一点是java中int型的范围是: -2147483648~2147483647,题目中最坏的情况,所有数的和能够达到1015所以要用Long型,Long型的范围是-9223372036854774808~9223372036854774807,足够了。

代码如下:

 1 import java.io.*;

 2 import java.util.*;

 3 import java.math.*;

 4 

 5 

 6 public class Solution {

 7     public static void main(String[] args) {

 8         Scanner in = new Scanner(System.in);

 9         int n = in.nextInt();

10         Long[] num = new Long[n];

11         Long array_sum = 0L;

12         Long weight = 0L;

13         for(int i = 0;i < n;i++){

14             num[i]= in.nextLong();

15             array_sum += num[i];

16             weight += (i+1) * num[i];

17         }

18         Long max = weight;

19         for(int i = 0;i < n;i++){

20             weight = weight - array_sum + n*num[i];

21             max = Math.max(max, weight);

22         }

23         

24         System.out.println(max);

25         

26         

27         

28       }

29 }

 

你可能感兴趣的:(rank)