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