Longest Increasing Subsequence
Given an integer array nums, return the length of the longest strictly increasing subsequence.
public int lengthOfLIS(int[] nums) {
if(nums==null || nums.length==0){
return 0;
}
int[] dp = new int[nums.length];
int max = 1;
for(int index=0; index<nums.length;index++){
dp[index]=1;
for(int dpIndex=0; dpIndex<index; dpIndex++){
if(nums[dpIndex]<nums[index]){
dp[index]=Math.max(dp[index],dp[dpIndex]+1);
max=Math.max(dp[index],max);
}
}
}
return max;
}
There is also an O(n log n) solution which uses a technique similar to patience sorting. It isn't simple but once you know the implementation it is natural. Maybe with leetcode difficulty inflation an interviewer may expect you to know this as well because it is such a well known problem.
public class Solution {
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
int len = 0;
for(int x : nums) {
int i = Arrays.binarySearch(dp, 0, len, x);
if(i < 0) i = -(i + 1);
dp[i] = x;
if(i == len) len++;
}
return len;
}
}
Related Problems
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.
If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.
Return the maximum coins you can collect by bursting the balloons wisely.
The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).
To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Return the knight's minimum initial health so that he can rescue the princess.
Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.