# 數組中存在的最大連續數

## 例

`arr[] = {2, 24, 30, 26, 99, 25}`
`3`

`arr[] = { -8, 9 , -1, -6, -5}`
`2`

## 算法

```1. Declare a set.
2. Do traversing of the array, and insert all the values of array into the Set.
3. Set output to 0.
4. Traverse the array from i=0, to i<n(length of the array).
1. Check if Set contains the arr[i].
1. If true, then pick the current array element and store it to temp.
2. While Set contains the temp, repeatedly increases the values of temp.
3. Find out the maximum between output and temp-arr[i] and store it into the output.
5. Return output.```

## 履行

### C ++程序查找數組中存在的最大連續數

```#include<iostream>
#include<unordered_set>

using namespace std;

int getMaxConsecutiveNumber(int arr[], int n)
{
unordered_set<int> SET;
for (int i = 0; i < n; i++)
SET.insert(arr[i]);

int output = 0;
for (int i = 0; i < n; i++)
{
if (SET.find(arr[i] - 1) == SET.end())
{
int temp = arr[i];

while (SET.find(temp) != SET.end())
temp++;

output = max(output, temp - arr[i]);
}
}
return output;
}
int main()
{
int arr[] = {2, 24, 30, 26, 99, 25 };
int n = sizeof(arr) / sizeof(int);
cout << "Largest Set found : "<<getMaxConsecutiveNumber(arr, n)<< endl;
return 0;
}
```
`Largest Set found : 3`

### Java程序查找數組中存在的最大連續數

```import java.util.HashSet;

class LargestConsecutiveSet
{
public static int getMaxConsecutiveNumber(int arr[], int n)
{
HashSet<Integer> SET = new HashSet<Integer>();
for (int i = 0; i < n; i++)
{
SET.add(arr[i]);
}
int output = 0;
for (int i = 0; i < n; i++)
{
if(SET.contains(arr[i]))
{
int temp = arr[i];
while (SET.contains(temp))
temp ++;

output = Math.max(output, temp - arr[i]);
}
}
return output;
}
public static void main(String[] args)
{
int arr[] = {2, 24, 30, 26, 99, 25};
int n = arr.length;
System.out.println("Largest Set found : "+getMaxConsecutiveNumber(arr, n));
}
}
```
`Largest Set found : 3`

## 複雜性分析以查找數組中存在的最大連續數

### 時間複雜度

O（N） 哪裡 “ n” 是數組中元素的數量。 因為我們使用了HashSet，它允許在固定時間內進行插入，刪除和搜索操作。

### 空間複雜度

O（N） 哪裡 “ n” 是數組中元素的數量。 我們在集合中存儲了N個元素，因此線性空間複雜度。