Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum Subarray which is larger than a Key

I have an array of integers (not necessarily sorted), and I want to find a contiguous subarray which sum of its values are minimum, but larger than a specific value K

e.g. :

input : array : {1,2,4,9,5} , Key value : 10

output : {4,9}

I know it's easy to do this in O(n ^ 2) but I want to do this in O(n)

My idea : I couldn't find anyway to this in O(n) but all I could think was of O(n^2) time complexity.

like image 793
Arian Avatar asked Jun 17 '13 21:06

Arian


People also ask

How do you find the minimum value in Subarray?

Find index of minimum value in a subarrayFinish writing the function indexOfMinimum , which takes an array and a number startIndex , and returns the index of the smallest value that occurs with index startIndex or greater.

How do you find the largest Subarray?

Simple Approach: Run a loop for i from 0 to n – 1, where n is the size of the array. Now, we will run a nested loop for j from i to n – 1 and add the value of the element at index j to a variable currentMax. Lastly, for every subarray, we will check if the currentMax is the maximum sum of all contiguous subarrays.

How do you find the minimum Subarray in C++?

Minimum Size Subarray Sum in C++ We have to find the minimal length of a contiguous subarray, of which the sum is greater or equal to s. If there isn't one,then return 0 instead. So if the array is like [2,3,1,2,3,4] and sum is 7, then the output will be 2.

What is contiguous Subarray?

A contiguous subarray is simply a subarray of an array with a condition that the elements of the subarray should be in exact sequence as the sequence of the elements in the array.


1 Answers

Let's assume that it can only have positive values.

Then it's easy.

The solution is one of the minimal (shortest) contiguous subarrays whose sum is > K.

Take two indices, one for the start of the subarray, and one for the end (one past the end), start with end = 0 and start = 0. Initialise sum = 0; and min = infinity

while(end < arrayLength) {
    while(end < arrayLength && sum <= K) {
        sum += array[end];
        ++end;
    }
    // Now you have a contiguous subarray with sum > K, or end is past the end of the array
    while(sum - array[start] > K) {
        sum -= array[start];
        ++start;
    }
    // Now, you have a _minimal_ contiguous subarray with sum > K (or end is past the end)
    if (sum > K && sum < min) {
        min = sum;
        // store start and end if desired
    }
    // remove first element of the subarray, so that the next round begins with
    // an array whose sum is <= K, for the end index to be increased
    sum -= array[start];
    ++start;
}

Since both indices only are incremented, the algorithm is O(n).

like image 189
Daniel Fischer Avatar answered Sep 20 '22 13:09

Daniel Fischer