给定一个无序数组arr, 其中元素可正、可负、可0。给定一个整数k,求arr所有子数组中累加和为k的最长子数组长度
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.HashMap; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] params = br.readLine().split(" "); int n = Integer.parseInt(params[0]), k = Integer.parseInt(params[1]); params = br.readLine().split(" "); int[] arr = new int[n]; for(int i = 0; i < n; i++) arr[i] = Integer.parseInt(params[i]); HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, -1); int presum = 0, maxLen = 0; for(int i = 0; i < n; i++){ presum += arr[i]; if(map.containsKey(presum - k)) maxLen = Math.max(maxLen, i - map.get(presum - k)); if(!map.containsKey(presum)) map.put(presum, i); } System.out.println(maxLen); } }
import java.util.Scanner; import java.util.HashMap; public class Main{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; for(int i = 0; i<n; i++){ arr[i] = sc.nextInt(); } System.out.println(getMaxLength(arr,k)); } public static int getMaxLength(int[] arr,int k){ if(arr==null||arr.length==0){ return 0; } HashMap<Integer,Integer> map=new HashMap<Integer,Integer>(); map.put(0,-1); int len=0; int sum=0; for(int i=0;i<arr.length;i++){ sum+=arr[i]; if(map.containsKey(sum-k)){ len=Math.max(i-map.get(sum-k),len); } if(!map.containsKey(sum)){ map.put(sum,i); } } return len; } }
package test; import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } // solution Map<Integer, Integer> map = new HashMap<>(); map.put(0, -1); int maxLen = 0, curSum = 0; for (int i = 0; i < n; i++) { curSum += arr[i]; if (!map.containsKey(curSum)) { map.put(curSum, i); } int gap = curSum - k; if (map.containsKey(gap)) { maxLen = Math.max(i - map.get(gap), maxLen); } } System.out.println(maxLen); } } /* 【示例1】 11 0 1 -2 1 1 1 -1 1 -1 1 -1 2 答案:9 解析:1 [-2 1 1 1 -1 1 -1 1 -1] 2 【示例2】 20 0 -1 1 0 4 5 -2 2 -2 2 -2 2 -4 4 5 -2 -2 -1 1 1 1 答案:12 解析:-1 1 0 4 5 [-2 2 -2 2 -2 2 -4 4 5 -2 -2 -1] 1 1 1 */
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++){ arr[i] = scanner.nextInt(); } Map<Integer,Integer> map = new HashMap<>(); map.put(0,-1); int sum = 0,maxLen = 0; for(int i=0;i<n;i++){ sum += arr[i]; if(!map.containsKey(sum)){ map.put(sum,i); } if(map.containsKey(sum-k)){ maxLen = Math.max(maxLen,i-map.get(sum-k)); } } System.out.print(maxLen); } }