I am new to programming and trying to solve the Longest Increasing Subsequence problem .
I am unsure if my algorithm can be memoized and if so I, I don't know what to memoize and where/how to cache a computed value just based on the current structure of the code. I am assuming this brute force approach is sound irrespective of the inefficiency for any use case. I have tried submitting it on leetcode and it fails on usecase 23 with a TLE.
Any advice on what to cache and where in the code to make this change will be greatly appreciated
The algorithm is as follows:
For each number at a given index, if it is greater than the previous number, I increase the length of the sequence by1
I do this then by not including the number and then checking the number with the previous value.
I repeat to find the max length until all possibilities are exhausted
class Solution {
public int lengthOfLIS(int[] nums) {
return helper(nums, Integer.MIN_VALUE, 0);
}
public int helper(int[] nums, int prev, int index ){
if(index >= nums.length) return 0;
else if(index == 0 || nums[index] > prev){
int max = 1;
int with = 1 + helper(nums, nums[index], index + 1);
int without = helper(nums, prev, index + 1);
max = Math.max(max, Math.max(with, without));
return max;
}
else{
return helper(nums, prev, index + 1);
}
}
}