
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.
The program begins by defining a helper function contains to determine if a squared value exists in the array. Then, for each element in the array, it calculates the squares sequentially. It keeps track of the maximum streak length, which is updated whenever a longer streak is 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.
1import java.util.Arrays;
2
3public class LongestSquareStreakDP {
4 public static int longestSquareStreak(int[] nums) {
5 Arrays.sort(nums);
6 int[] dp = new int[nums.length];
7 Arrays.fill(dp, 1);
8
9 int maxLength = -1;
10 for (int i = 0; i < nums.length; i++) {
11 for (int j = 0; j < i; j++) {
12 if (nums[i] == nums[j] * nums[j]) {
13 dp[i] = Math.max(dp[i], dp[j] + 1);
14 }
15 }
16 if (dp[i] > 1) {
17 maxLength = Math.max(maxLength, dp[i]);
18 }
19 }
20
21 return maxLength;
22 }
23
24 public static void main(String[] args) {
25 int[] nums = {4, 3, 6, 16, 8, 2};
26 System.out.println(longestSquareStreak(nums));
27 }
28}The Java solution features a sorted array with a dynamic programming array to store streak lengths. It updates dp iteratively to locate the maximum valid streak utilizing square checks.