fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4.  
  5. public static int countShortestSubarraysWithSumK(int[] nums, int k) {
  6. int n = nums.length;
  7. int minLength = Integer.MAX_VALUE, count = 0;
  8.  
  9. for (int start = 0; start < n; start++) {
  10. int sum = 0;
  11. for (int end = start; end < n; end++) {
  12. sum += nums[end];
  13. if (sum == k) {
  14. int length = end - start + 1;
  15. if (length < minLength) {
  16. minLength = length;
  17. count = 1;
  18. } else if (length == minLength) {
  19. count++;
  20. }
  21. }
  22. }
  23. }
  24.  
  25. return count;
  26. }
  27.  
  28. public static int countLargestSubarraysWithSumK(int[] nums, int k) {
  29. int n = nums.length;
  30. int maxLength = 0, count = 0;
  31.  
  32. for (int start = 0; start < n; start++) {
  33. int sum = 0;
  34. for (int end = start; end < n; end++) {
  35. sum += nums[end];
  36. if (sum == k) {
  37. int length = end - start + 1;
  38. if (length > maxLength) {
  39. maxLength = length;
  40. count = 1;
  41. } else if (length == maxLength) {
  42. count++;
  43. }
  44. }
  45. }
  46. }
  47.  
  48. return count;
  49. }
  50.  
  51. public static void main(String[] args) {
  52. int[] nums = {1, 2, 3, 4, 2, 5};
  53. int k = 5;
  54.  
  55. System.out.println("Shortest subarrays with sum " + k + ": " + countShortestSubarraysWithSumK(nums, k));
  56. System.out.println("Largest subarrays with sum " + k + ": " + countLargestSubarraysWithSumK(nums, k));
  57. }
  58. }
Success #stdin #stdout 0.15s 55400KB
stdin
Standard input is empty
stdout
Shortest subarrays with sum 5: 1
Largest subarrays with sum 5: 1