What is contiguous subarray

I am trying to study contiguous subarray but I am not getting any study material which explains this concept.

But I found one example with says that Given the array [-2,1,-3,4,-1,2,1,-5,4] the contiguous subarray is [4,-1,2,1]

Can anyone explain on what bases they are saying contiguous subarray is [4,-1,2,1]

4 Answers

It isn't the contiguous subarray, there are many. It's just a subsequence without skipping any elements. E.g. [-2, 1], [-2, 1, -3], [2, 1, -5] are all contiguous subarrays of this array, but [2, 1, 4] isn't.

3

Note: So I kept my original answer and extra thoughts here:

The actual definition of contiguous subarray (as others have answered) is any sub series of elements in a given array that are contiguous ie their indices are continuous.

So given [1,2,3,4,5,6]:

[1,2,3], [3,4], [3,4,5,6] are all valid contiguous subarrays. Any algorithm can be used to generate the subarrays.

Personal note: What was confusing for me was most explanations either use or reference a specific problem or condition set to generate the subarrays. Most don't specifically state there's no direct relationship between the problem and the definition of contiguous subarrays.

For me it's the same as asking:

Q: "What does + do?"

A: "4+4=8"

Me: "OK, so I can only use + with 4, got it."

On my travels I'd see answers like this:

basically the sum of contiguous array must be greater, if you will try to add the all elements of array it will give you lowest sum, but if you will add this specific range in continuity you will get the greatest sum we can make out of this array.

Which is referring to some specific problem that uses contiguous subarrays, but no one was calling this out, so to a noob you could infer that contiguous subarrays has some further meaning.

This is how my brain worked to grok the definition, so hopefully it helps someone else out.

1

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. for example if the array is [1,2,3,4,5] then [1,3,5] is a subarray of the array, but not a contiguous subarray since the sequence does not match as the elements 2 and 4 are skipped. [1,2,3] will be one of the contiguous subarrays.

basically the sum of contiguous array must be greater, if you will try to add the all elements of array it will give you lowest sum, but if you will add this specific range in continuity you will get the greatest sum we can make out of this array.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like