703222. Distinct Adjacent Element
Distinct Adjacent Element
Slug: distinct-adjacent-element2121 Difficulty: Basic Id: 703222 Topic Tags: Arrays, Data Structures Company Tags: None
Summary
Given an array of integers, we need to find the maximum number of distinct elements that can be obtained by selecting adjacent elements from the array. For example, if the input array is [1, 2, 3, 4], the output should be 3 because we can select the first two distinct elements (1 and 2) and the last two distinct elements (3 and 4).
Detailed Explanation
To solve this problem, we will iterate through the array and keep track of the maximum number of distinct elements that can be obtained by selecting adjacent elements. We will maintain a variable count to store the count of distinct elements.
Here is the step-by-step breakdown of the solution:
- Initialize
countto 0. - Iterate through the array from left to right.
- For each element, check if it is different from the previous element (or the first element if this is the first iteration).
- If the current element is different, increment
count. - Return
countas the maximum number of distinct elements that can be obtained.
Here's an ASCII art diagram to illustrate the solution:
1 2 3 4 5
^
|
| Count = 0
| Select 1 (different from previous)
| Count = 1
| Select 2 (different from previous)
| Count = 2
| Select 3 (same as previous)
| Count = 2
| Select 4 (different from previous)
| Count = 3
| Select 5 (different from previous)
| Count = 4
The time complexity of this solution is O(n), where n is the size of the input array. The space complexity is O(1) as we only use a constant amount of space to store the count variable.
Optimized Solutions
Java
public int distinctAdjacentElements(int[] arr) {
if (arr.length == 0) return 0;
int count = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
count++;
}
}
return count + 1;
}