【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.

image1

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 }

 

转载于:https://www.cnblogs.com/sunshineatnoon/p/3887557.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值