Untitled

for longest consecutive
 avatar
unknown
c_cpp
a month ago
663 B
1
Indexable
int longestConsecutive(vector<int>& nums) {
	int n = nums.size();
	if (n == 0) return 0;

	// Remove duplicates and sort the array
	sort(nums.begin(), nums.end());

	int longest = 1; // At least one element is in the array
	int currentStreak = 1;

	for (int i = 1; i < n; i++) {
		// If current number is consecutive to the previous one
		if (nums[i] == nums[i - 1] + 1) {
			currentStreak++;
		}
		// If current number is a duplicate, skip it
		else if (nums[i] != nums[i - 1]) {
			longest = max(longest, currentStreak);
			currentStreak = 1; // Reset streak count
		}
	}

	// Check the last streak
	return max(longest, currentStreak);
}
Leave a Comment