For example, {1, 4, 45, 6, 0, 19}
and the number 51
should return 3
, because the number of elements in the smallest subarray which together are greater than 51
are 3:
{4,45,6}`.
{7, 2, 5, 10, 1}
and the number 9
should return 1
, because the number of the elements in the smallest subarray possible that is greater than 9
is {10}
.
If array is null or empty, or the array has no subarray that is greater than the given number, the method has to return -1. I'm not allowed to use array package from java.util. My goal is to execute the method in O(n) time. This is my code so far, if the array has no subarray greater than the given number, it returns an OutofBounds error. Anyone has a clue?
public static int smallestSubSum(int arr[], int x) {
int left = 0, right = 1, smallest = 0;
int sum = arr[right];
for (int i = 1; i < arr.length; i++) {
if (sum > x)
smallest = left - right;
else
right++;
sum += arr[right];
if (sum > x && left - right < smallest) {
smallest = left - right;
left++;
} else
sum -= arr[left];
left++;
if (sum > x && left - right < smallest)
smallest = left - right;
}
return smallest;
}
Edit: Perhaps I should explain what I tried to do with my code, basically I wanted the sum to hold the first two elements in the code, and then compare with each 'if' iteration if the sum of the current elements are greater or less than X, if not I raise the right element to go further, if yes I erase the first element, the 'left' one.
The array of {1, 4, 45, 6, 0, 19} and the number 51 returns 2, even though the result should be 3. I don't know why, because my right reaches the index 3 which is 6 and the left one reaches index 1 which is 4, so the result should indeed be {4,45,6} but it doesn't get to it.