Last active
October 14, 2019 18:29
-
-
Save thmain/c3076e391c5ed692bc19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MinimumSubArraySum { | |
public void minSubArray(int[] arrA, int x) { | |
int start = 0; | |
int ansEnd = 0; | |
int ansStart = 0; | |
int currSum = 0; | |
int minLen = arrA.length; | |
boolean found = false; | |
for (int i = 0; i <= arrA.length; i++) { | |
while (currSum >= x) { | |
found = true; | |
currSum = currSum - arrA[start]; | |
if (i - start <= minLen) { | |
minLen = (i - start); | |
ansEnd = i; | |
ansStart = start; | |
} | |
start++; | |
} | |
if (i < arrA.length) { | |
currSum = currSum + arrA[i]; | |
} | |
} | |
if(found){ | |
System.out.println("Minimum length of subarray to get " + x + " is : " | |
+ minLen); | |
System.out.print("SubArray is:"); | |
for (int i = ansStart; i < ansEnd; i++) { | |
System.out.print(" " + arrA[i]); | |
} | |
}else{ | |
System.out.println("No subarray to get " + x); | |
} | |
} | |
public static void main(String[] args) throws java.lang.Exception { | |
int[] arrA = { 1, 5, 4, 40 }; | |
MinimumSubArraySum i = new MinimumSubArraySum(); | |
i.minSubArray(arrA, 50); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment