fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static int[] largestSubarraySumK(int[] nums, int k) {
  5. int maxLen = 0;
  6. int[] result = {-1, -1};
  7.  
  8. for (int i = 0; i < nums.length; ++i) {
  9. int currentSum = 0;
  10. for (int j = i; j < nums.length; ++j) {
  11. currentSum += nums[j];
  12. if (currentSum == k && (j - i + 1) > maxLen) {
  13. maxLen = j - i + 1;
  14. result[0] = i + 1; // 1-based index
  15. result[1] = j + 1;
  16. }
  17. }
  18. }
  19. return result;
  20. }
  21.  
  22. public static void main(String[] args) {
  23. int[] nums = {1, 2, 3, 4, 5, -1, 6};
  24. int k = 9;
  25. int[] result = largestSubarraySumK(nums, k);
  26. if (result[0] != -1) {
  27. System.out.println("Largest subarray with sum " + k + " is from index " + result[0] + " to " + result[1]);
  28. } else {
  29. System.out.println("No subarray with sum " + k);
  30. }
  31. }
  32. }
Success #stdin #stdout 0.13s 57940KB
stdin
Standard input is empty
stdout
Largest subarray with sum 9 is from index 2 to 4