【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 }
复制代码

 

posted @   SunshineAtNoon  阅读(425)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示