fork download
  1. import java.util.HashMap;
  2. import java.util.Map;
  3.  
  4. public class Main {
  5.  
  6. public static int[] findLargestSubarray(int[] nums, int k) {
  7. Map<Integer, Integer> sumMap = new HashMap<>();
  8. sumMap.put(0, -1);
  9.  
  10. int sum = 0, maxLen = 0;
  11. int[] result = {-1, -1};
  12.  
  13. for (int j = 0; j < nums.length; j++) {
  14. sum += nums[j];
  15.  
  16. if (sumMap.containsKey(sum - k)) {
  17. int i = sumMap.get(sum - k);
  18. if (j - i > maxLen) {
  19. maxLen = j - i;
  20. result[0] = i + 1;
  21. result[1] = j;
  22. }
  23. }
  24.  
  25. sumMap.putIfAbsent(sum, j);
  26. }
  27.  
  28. return result;
  29. }
  30.  
  31. public static void main(String[] args) {
  32. int[] nums = {1, 2, 3, 4, 5, -1, -4};
  33. int k = 9;
  34. int[] result = findLargestSubarray(nums, k);
  35.  
  36. if (result[0] != -1) {
  37. System.out.println("Largest subarray with sum " + k + " is from index " + result[0] + " to " + result[1]);
  38. } else {
  39. System.out.println("No subarray with sum " + k);
  40. }
  41. }
  42. }
  43.  
Success #stdin #stdout 0.21s 55936KB
stdin
Standard input is empty
stdout
Largest subarray with sum 9 is from index 1 to 6