Given an unsorted array of integers, find the length of longest increasing subsequence. For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
intlengthOfLIS(int* nums, int numsSize){ // sanity check if(numsSize <= 0) { return0; } // dp[idx]: the length of the LIS ending with the idx-th element int dp[numsSize]; // prev[idx]:record the previous index of the LIS ending with the idx-th element int prev[numsSize]; for(int idx=0; idx<numsSize; idx++) { // the maximum length of previous index LIS ending with an element not greater than current element int localIdxMax = 0; for(int i=0; i<idx; i++) { if(nums[i] < nums[idx] && dp[i] > localIdxMax) { localIdxMax = dp[i]; prev[idx] = i; } } dp[idx] = localIdxMax + 1; } // the longest increasing subsequence should ending with one index-th element int totalMax = 0; for(int idx=0; idx<numsSize; idx++) { if(dp[idx] > totalMax) { totalMax = dp[idx]; } } return totalMax; }
/* * finds a minimum value greater than findingNum in findingArray[1, 2, ..., findingArraySize] and returns its position * findingArray should be in order */ intbinarySearch(int* findingArray, int findingArraySize, int findingNum){ int begin = 1; int end = findingArraySize; while(begin <= end) { int mid = begin + (end - begin)/2; if(findingArray[mid] > findingNum) { end = mid - 1; } elseif(findingArray[mid] < findingNum) { begin = mid + 1; } else { // return the same value position for covering return mid; } } // return postion to insert after return begin; }
intlengthOfLIS(int* nums, int numsSize){ // sanity check if(numsSize < 1) { return0; } // A[i=1, 2, ..., maxLen]: the minimum value of the end element of the i-length increasing sequence int A[numsSize+1]; int maxLen; maxLen = 1; A[1] = nums[0]; for(int idx=1; idx<numsSize; idx++) { if(nums[idx] > A[maxLen]) { maxLen += 1; A[maxLen] = nums[idx]; } else { int pos = binarySearch(A, maxLen, nums[idx]); A[pos] = nums[idx]; } } return maxLen; }