702683. Longest sub-sequence such that difference between adjacents is one
Longest Sub-sequence Such That Difference Between Adjacents is One
Summary
Given an array of integers, find the longest sub-sequence such that the difference between adjacent elements is one. This problem involves arrays and data structures, requiring a logical approach to identify the longest sub-sequence.
Detailed Explanation
The given problem can be solved by using a two-pointer technique. Initialize two pointers, i and j, at the start of the array. Compare the elements at positions i and j. If their difference is one, increment i and decrement j to maintain the sub-sequence. Continue this process until no more increments or decrements are possible.
Here's a step-by-step breakdown:
- Initialize two pointers,
iandj, at the start of the array. - Compare the elements at positions
iandj. If their difference is one, incrementiand decrementj. - Continue this process until no more increments or decrements are possible.
Time complexity: O(n), where n is the length of the array. This is because we only iterate through the array once. Space complexity: O(1), as we do not require any extra space.
Optimized Solutions
Java
java
public class Solution {
public int longestSubsequence(int[] nums) {
if (nums.length == 0) return 0;
int i = 0, j = nums.length - 1;
int maxLength = 1;
while (i < j) {
if (Math.abs(nums[i] - nums[j]) == 1) {
maxLength++;
i++;
j--;
} else if (nums[i] < nums[j]) {
i++;
} else {
j--;
}
}
return maxLength;
}
}
Python
python
def longest_subsequence(nums):
if not nums:
return 0
i, j = 0, len(nums) - 1
max_length = 1
while i < j:
if abs(nums[i] - nums[j]) == 1:
max_length += 1
i += 1
j -= 1
elif nums[i] < nums[j]:
i += 1
else:
j -= 1
return max_length
C++
cpp
#include <vector>
using namespace std;
int longestSubsequence(vector<int>& nums) {
if (nums.empty()) return 0;
int i = 0, j = nums.size() - 1;
int maxLength = 1;
while (i < j) {
if (abs(nums[i] - nums[j]) == 1) {
maxLength++;
i++;
j--;
} else if (nums[i] < nums[j]) {
i++;
} else {
j--;
}
}
return maxLength;
}
JavaScript
javascript
function longestSubsequence(nums) {
if (!nums.length) return 0;
let i = 0, j = nums.length - 1;
let maxLength = 1;
while (i < j) {
if (Math.abs(nums[i] - nums[j]) === 1) {
maxLength++;
i++;
j--;
} else if (nums[i] < nums[j]) {
i++;
} else {
j--;
}
}
return maxLength;
}
These optimized solutions provide the longest sub-sequence with a difference of one between adjacent elements.
Not available