Skip to content

15-Ab/Leetcode-Daily-Challenge

Repository files navigation

Leetcode Daily Challenge Solutions

This is my attempt to make the coding experience easier for you guys so that you can easily learn what to do in today's leetcode challenge.

Always here to assist you guys.

Today's 05-01-24 Problem Link

Intuition

  • Dynamic Programming
    • My algorithm must use dynamic programming to efficiently update and maintain the longest increasing subsequence.
  • Greedy Choice
    • My algorithm must makes a greedy choice to update the current longest increasing subsequence (a) based on the incoming elements from the input array (nums).

Approach

  • ArrayList 'a'
    • I used 'a' to store the current longest increasing subsequence.
    • It starts as an empty ArrayList.
  • Iterating through nums
    • My code iterates through each element 's' in the input array nums.
    • For each element :
      • If a is empty or s is greater than the last element in a, add s to a (greedy choice as it contributes to increasing subsequence).
      • Otherwise, found the correct position for s in a using the bs function, and update the element at that position with s.
  • Binary Search Function 'bs':
    • The 'bs' function performs a binary search on the sorted ArrayList 'a' to find the index of 's' or the index where 's' should be inserted.
    • If 's' is found, it returns the index. If not found, it returns the negation of the insertion point. This insertion point is used to update the current increasing subsequence.
  • Return Result :
    • Finally, I returned the length of the longest increasing subsequence is the size of the ArrayList a.

  • If you're still having trouble understanding what the binary search functions does here, I would suggest you to please go through this site search here for binarySearch

Have a look at the code , still have any confusion then please let me know in the comments Keep Solving.:)

Complexity

  • Time complexity : $$O(l*log(l))$$
  • Space complexity : $$O(l)$$

$$l$$ : length of array.

Code

class Solution {
    public int lengthOfLIS(int[] nums) {
        
        ArrayList<Integer> a = new ArrayList<>();
        for( int s : nums){
            if( a.isEmpty() || s > a.get( a.size() - 1) ){
                a.add(s);
            } 
            else{
                a.set( bs(a, s) , s);
            }
        }
        return a.size();
    }

    static int bs( ArrayList<Integer> a, int s){
        int in = Collections.binarySearch(a, s);
        if( in < 0){
            return - in - 1;
        }
        return in;
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy