Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active October 14, 2019 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/c3076e391c5ed692bc19 to your computer and use it in GitHub Desktop.
Save thmain/c3076e391c5ed692bc19 to your computer and use it in GitHub Desktop.
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