思路:先用冒泡排序从小到大,然后再对里面数据进行整理。 import java.util.Scanner; /** * @author shkstart * @create 2021-12-06-9:50 */ public class Max { public static void paixu(int[] arr){ int m; for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { m = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = m; } } } } public static void bianhuan(int[] arr,int negativenumber,int num1) { boolean zero = false; if (negativenumber > num1) { for (int i = 0; num1 != 0; i++) { arr[i] = -arr[i]; num1--; } } else if (negativenumber == num1) { for (int i = 0; i < arr.length; i++) { if (arr[i] < 0) { arr[i] = -arr[i]; } } } else if (negativenumber < num1) { if ((num1 - negativenumber) % 2 == 0) { for (int i = 0; i < arr.length; i++) { if (arr[i] < 0) { arr[i] = -arr[i]; } } } else { for (int i = 0; i < arr.length; i++) { if(arr[i] == 0){ zero = true; } if (arr[i] < 0) { arr[i] = -arr[i]; } } if(zero = false)arr[0] = -arr[0]; } } } public static void main(String[] args) { int num, num1, m, negativenumber = 0, sum = 0; Scanner scan = new Scanner(System.in); System.out.println("你要输入几个数"); num = scan.nextInt(); System.out.println("请输入你要输入的数"); int[] arr = new int[num]; for (int i = 0; i < num; i++) { arr[i] = scan.nextInt(); } System.out.println("请输入取反次数"); num1 = scan.nextInt(); paixu(arr); for (int i = 0; i < arr.length; i++) { if (arr[i] < 0) { negativenumber++; } } bianhuan(arr,negativenumber,num1); for (int i = 0; i < arr.length; i++) { sum += arr[i]; } System.out.println(sum); } }
输入一个整数数组和一个整数k,按以下方式修改该数组1.选择某个下标 i 并将 nums[i] 替换为 -nums[i]2.重复这个过程恰好 k 次。可以多次选择同一个下标 i 。返回数组可能的最大和
最新推荐文章于 2022-07-10 23:28:31 发布