0

I have a vector<int> num, I want to get the size of longest subarray with the sum less than or equal to k.

My approach: O(n^2). Repeat for every element in the array.

Can we do better?'

Note: I don't need the actual longest subarray, only its size. So the return value is int.

asked Oct 23, 2016 at 1:36
1
  • Can the elements be negative? Commented Oct 23, 2016 at 3:11

1 Answer 1

1

Assuming, that the vector contains only non-negative integers:

int getLargestSubsequenceSize(vector<int>& myVector, int k){
 int maxCount = 0;
 int i=0,j=0;
 int sum = 0;
 while(j < myVector.size()){
 sum += myVector[j];
 if(sum > k){
 int currCount = j-i;
 if(currCount > maxCount)
 maxCount = currCount;
 sum -= myVector[i];
 i++;
 } 
 j++;
 }
 return maxCount;
}

The above function has two indexes (i,j). j will increment and add current number to the sum until sum becomes greater than k. Once it is greater, we will calculate the length of this sub-sequence and check whether it is bigger than previous subsequence. If yes, we will update the maxCount. Now, we will increment the lower index (i) and repeat the process. Time Complexity = O(n)

Robert Harvey
201k55 gold badges469 silver badges682 bronze badges
answered Oct 23, 2016 at 3:56
1
  • 2
    Explain how this works, and why it's better than O(n^2) Commented Oct 23, 2016 at 4:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.