java - 最终和初始总和之间的最大差异
问题描述
我是编程新手,无法解决一项任务。我有几个输入示例。第一行包含两个数字 m(纸上的位数,1<m<1000)和 h(操作次数的限制,1<h<1000)。我有机会,不超过 h 次,从一张纸上取任何数字(表示 m),然后画在一个旧数字上,并在其位置写一个新的任意数字。我可以将纸上所有数字的总和增加多少?
第一个例子:
输入:
5 2 //m 和 h
1 3 1 4 5 //m = 5,所以我可以添加5个任意数字并且h = 2,所以我可以更改2个数字
输出:
16 // 因为我把 1 和 1 改成了 9 和 9,所以差 8 和 8 和是 16
第二个例子:
输入:
3 1
99 5 85
输出:
10 //85到95,所以相差10
第三个例子:
输入:
1 10
9999
输出:
0 // 没什么可改变的
我现在拥有的:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int m = sc.nextInt();
int h = sc.nextInt();
System.out.println("Entered: " + m);
System.out.println("Entered: " + h);
int[] numbers = new int[m];
for(int i = 0; i < m; ++i) {
numbers[i] = sc.nextInt();
}
Arrays.sort(numbers);
//here is my logic: I am changing 1 to 9
for (int i = 0; i < h; i++) {
if (numbers[i] < 10) {
numbers[i] = 9;
}
else if (numbers[i] > 9 and numbers[i] < 100) {
numbers[i] = 99;
}
}
sc.close();
我的逻辑适用于第一个示例,但对于第二个示例则不起作用。如果我使用正确的逻辑或者有什么更简单的方法来解决这个问题,你能帮我吗?提前致谢。
解决方案
将每个输入数字分解为其数字乘以适当的 10 的幂。按 10 的幂降序排序,数字升序。按此顺序应用您的操作。
例如,876、12、42 -> 800、70、6、10、2、40、2 -> 800、10、40、70、2、2、6。
推荐阅读
- avd - 我的电脑不支持HAXM,有什么替代方案吗?
- scala - log4j 警告:找不到记录器的附加程序(org.apache.kafka.clients.producer.ProducerConfig)
- oauth-2.0 - LinkedIn OAuth2.0 使会话无效/强制重新授权
- python - 使用具有 2 个主键模型的基于类的视图 UpdateView
- r - 基于多列检索唯一记录的数据框
- javascript - Webpack Bundle 文件没有 CSS 样式和 UI 组件
- azure - Azure SQL 数据库 - 禁用 SQL Server 身份验证模式
- javascript - D3.js:使用滑块更改导入文件
- c# - Viewstate 验证失败 Asp.net
- vsphere - Vmware 中的 PSC 和 VC