Sunday, August 4, 2019

300. Longest Increasing Subsequence

Here is the link.

I have a mock interview and worked on the algorithm to find if there are three increasing subsequence in the array on August 4, 2019 10:00 PM. I found out that I solved the partial solution and then the interviewer told me that it is special case of longest increasing subsequence. And also he explained to me how to use binary search to solve it using O(nlogn) time.
I have to work hard to review the algorithm. The first step is to share my last submission back in 2017. And then I plan to study more on various solutions on the algorithm.
public class Solution {
    public int LengthOfLIS(int[] nums) {
        int size = nums.Length;

            if (size == 0) { 
                return 0; 
            } 

            var subsequence = new int[size];

            int length = 1;
            for (int i = 0; i < size; ++i) 
            {
                var current = nums[i];
                subsequence[i] = 1; 

                // get maximum value from all options
                for (int j = 0; j < i; ++j) 
                {
                    var visit = nums[j];
                    if (visit < current)
                    {
                        subsequence[i] = Math.Max(subsequence[i], subsequence[j] + 1);
                    }
                }

                // update the length if need
                length = Math.Max(length, subsequence[i]);
            }

            return length;
        }    
}


No comments:

Post a Comment