【蓝桥云课】人性总是贪婪的

题目描述:

假如整数n表示当前奖池中已经有的钱的总数,给你一个一夜暴富的机会:请你从n中删除m个数字,余下的数值对应的金额就是你能够拿走的钱,我们知道人性都是贪婪的,那么请编程帮小明使得余下的数字按原次序组成的新数最大,比如当n=92081346718538. m=10时,则新的最大数是9888

样例输入

92081346718538 10
1008908 5

样例输出

9888
98

程序代码:

import java.util.Scanner;

public class selectMoney {
          
   

	public static void main(String[] args) {
          
   
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
          
   
			String n = sc.next();// 用字符串的形式读入进来
			int m = sc.nextInt();// 要删除的个数
			int save = n.length() - m;// 保留的个数,删除问题转换成保留的问题
			String max = "";// 存放最后我们选择要保留的字符
			char[] a = n.toCharArray();// n变成字符数组
			int last_select_pos = -1;// 开始的时候一个都没有被选中+1刚好对应0的位置
			for (int i = 1; i <= save; i++) {
          
   // 分save次去选择每次可选的最大字符
				char big = 0;// 假定本轮要选的字符是无穷小
				for (int j = last_select_pos+1; j < a.length - (save - i); j++) {
          
   
					if (a[j] > big) {
          
   
						big = a[j];
						last_select_pos = j;// 记录当前找到的最大的位置
					}
				}
				max = max + big;// 每一次都把找到的可选的最大的字符串追加到尾部
			}
			System.out.println(max);
		}
	}
}

以n=92081346718538. m=10为例,过程如下:

下标 0 1 2 3 4 5 6 7 8 9 10 11 12 13 n 9 2 0 8 1 3 4 6 7 1 8 5 3 8

n.length=14,删除m=10个,还剩4个 max=“” ,last_select_pos =-1 ①从下标0到下标10,找到最大的数为9,last_select_pos = 0 ②从下标1到下标11,找到最大的数为8,last_select_pos = 3 ③从下标4到下标12,找到最大的数为8,last_select_pos = 10 ④从下标11到下标13,找到最大的数为8,last_select_pos = 13

最后结果为9888

经验分享 程序员 微信小程序 职场和发展