Sponsored
Sponsored
This approach leverages a HashSet for quick access to elements and checks subsequent squares in the sequence. We iterate over each number in the array, and for each number, keep finding its squares while incrementing the length of the streak. The longest streak is tracked and returned at the end.
Time Complexity: O(n^1.5) in worst-case due to nested loops and nested search.
Space Complexity: O(1) extra space for auxiliary storage as in-place checks are performed.
1import java.util.HashSet;
2import java.util.Set;
3
4public class LongestSquareStreak {
5 public static int longestSquareStreak(int[] nums) {
6 Set<Integer> numSet = new HashSet<>();
7 for (int num : nums) {
8 numSet.add(num);
9 }
10 int maxLength = -1;
11
12 for (int num : nums) {
13 int length = 1;
14 int current = num;
15 while (numSet.contains(current * current)) {
16 current *= current;
17 length++;
18 }
19 if (length > 1) {
20 maxLength = Math.max(maxLength, length);
21 }
22 }
23 return maxLength;
24 }
25
26 public static void main(String[] args) {
27 int[] nums = {4, 3, 6, 16, 8, 2};
28 System.out.println(longestSquareStreak(nums));
29 }
30}
The Java solution employs a HashSet
to quickly verify the presence of subsequent squared elements in the sequence, enhancing time efficiency. It iterates through each element, calculates the length of potential square streaks, and retains the maximum length found.
This approach uses dynamic programming to store intermediate results regarding the longest square streak ending at each number. Sorting the array helps in ensuring that every subsequent square evaluated is in a larger-than relationship compared to previous elements, thus contributing to the streak length.
Time Complexity: O(n^2) due to nested loops used in the calculation of dp array.
Space Complexity: O(n) for managing the dp array.
1#include <vector>
#include <algorithm>
using namespace std;
int longestSquareStreakDP(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> dp(nums.size(), 1);
int maxLength = -1;
for (size_t i = 0; i < nums.size(); ++i) {
for (size_t j = 0; j < i; ++j) {
if (nums[i] == nums[j] * nums[j]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
if (dp[i] > 1) {
maxLength = max(maxLength, dp[i]);
}
}
return maxLength;
}
int main() {
vector<int> nums = {4, 3, 6, 16, 8, 2};
cout << longestSquareStreakDP(nums) << endl;
return 0;
}
The C++ implementation uses sorting to facilitate processing, and constructs a dp
vector dynamically storing maximum streak lengths ending at each position, hence optimizing overall results computation.