对于如此变态的数据范围,我也不得不动用同样变态的 BigDecimal
了
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] nums = scanner.next().split(","); int n = nums.length; // dp[i] -> 除 nums[i] 以外的其余所有元素的乘积 BigDecimal[] dp = new BigDecimal[n]; dp[0] = BigDecimal.valueOf(1); for (int i = 1; i < n; i++) { dp[i] = dp[i - 1].multiply(BigDecimal.valueOf(Integer.parseInt(nums[i - 1]))); } BigDecimal temp = BigDecimal.valueOf(1); for (int i = n - 1; i >= 0; i--) { dp[i] = dp[i].multiply(temp); temp = temp.multiply(BigDecimal.valueOf(Integer.parseInt(nums[i]))); } BigDecimal max = dp[0]; int idx = 0; for (int i = 1; i < n; i++) { if (dp[i].compareTo(max) > 0) { max = dp[i]; idx = i; } } System.out.println(idx); } }
分三种情况讨论 import java.util.*; import java.math.*; public class Main { //移调数组一个元素使得数组乘积最大 private static int maxRemove(int[] nums) { BigInteger mlt = new BigInteger("1"); for (int n: nums) { if (n == 0) { continue; } mlt = mlt.multiply(BigInteger.valueOf(n)); } int res = -1; BigInteger max = BigInteger.valueOf((Integer.MIN_VALUE)); for (int i = 0; i < nums.length; i++) { BigInteger cur = mlt.divide(BigInteger.valueOf(nums[i])); if (cur.compareTo(max) > 0) { res = i; max = cur; } } return res; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); String[] ss = s.split(","); int n = ss.length; int[] nums = new int[n]; boolean hasZero = false; int cntZero = 0; for (int i = 0; i < n; i++) { nums[i] = Integer.parseInt(ss[i]); if (nums[i] == 0) { hasZero = true; cntZero++; } } sc.close(); if (cntZero > 1) { System.out.println(0); //随便移除谁都是0 } else if (cntZero == 1) { BigInteger mlt = new BigInteger("1"); int zeroIdx = -1; for (int i = 0; i < n; i++) { if (nums[i] != 0) { mlt = mlt.multiply(BigInteger.valueOf(n)); } else { zeroIdx = i; } } System.out.println(mlt.compareTo(BigInteger.valueOf(0)) > 0 ? zeroIdx : 0); } else { System.out.println(maxRemove(nums)); } // int[] nums = {4,3,5,-7,-21,9,-1,-5,6,0}; } }
public static String removeMin(List<Integer> list) { int min = list.get(0); HashSet<Integer> set = new HashSet<>(); int num=0,index=0; for (int i = 0; i < list.size(); i++) { if (!set.add(list.get(i))) { num=list.get(i); } if (list.get(i) - min < 0) { min = list.get(i); index=i; } } return "移除的元素为"+min+",下标是"+index+",相同元素第一次出现的是"+num; }
public static Integer removeElement(List<Integer> list) { if (CollectionUtils.isNotEmpty(list)) { int index = 0; int min = list.get(0); for (int i = 1; i < list.size(); i++) { if (list.get(i) - min < 0) { min = list.get(i); index = i; } } list.remove(index); return index; } return null; }