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.
1using System;
2using System.Collections.Generic;
3
4public class Program {
5 public static int LongestSquareStreak(int[] nums) {
6 HashSet<int> numSet = new HashSet<int>(nums);
7 int maxLength = -1;
8
9 foreach (int num in nums) {
10 int length = 1;
11 int current = num;
12 while (numSet.Contains(current * current)) {
13 length++;
14 current *= current;
15 }
16 if (length > 1) {
17 maxLength = Math.Max(maxLength, length);
18 }
19 }
20 return maxLength;
21 }
22
23 public static void Main() {
24 int[] nums = {4, 3, 6, 16, 8, 2};
25 Console.WriteLine(LongestSquareStreak(nums));
26 }
27}
The C# solution utilizes a HashSet
for efficient lookup operations of squares. Each number is checked for potential square streaks, and the current longest streak is maintained.
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.