# Leetcode 300 Longest Increasing Subsequence

Here the question:

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

• There may be more than one LIS combination, it is only necessary for you to return the length.
• Your algorithm should run in O(n2) complexity.

There is a more simple algorithm to solve this question. But we would like to learn about Dynamic Programming. So we will take the O(n2) solution.

### Dynamic Programming

A condition necessary for Dynamic Programming:

It means that the optimal result is constructed by the optimal result of its subproblem.

Another condition:

It means that we can reuse the result of the subproblem of the problem that we are facing.

If a problem tallies with the two conditions, then the problem can be solved by Dynamic Programming.

### Solution

The prototype of this function is

`A` is an array, `length` is the length of array `A`.

For overlapping subproblems property, to reuse the result of subproblems, we have to store the result of subproblems. We assigned an array with enougn slots for results.

The first element must be a valid increasing subsequence because there is only one element.

So for the problem with only one element, we have the result:

And then, for the next subproblems, we can execute a loop to solve them one by one.

By using this loop, we can solve firstly F, then F… until F[length-1].

For each F[k], we search all previous elements to find out which is smaller than `A[k]`, the element on which we pause. If an element is smaller than `A[k]`, it means that at worst, we have an increasing sequence with two elements (`A[k]` and the element itself), so it’s possible to increase the length at the position of that element by 1 to fill `F[k]`.

We have one slot to be filled, to find out the longest one, we can pick up the largest length at the positions before `k`, and assign `length+1` to `F[k]`. So we can garantee that, at this position, there is the length of longest increasing sequence, which is the optimal solution of such a problem(or subproblem).

So we can mix the process of finding the largest length and the process of finding the possible lengths.

It should be noticed that we check the existence of max length with the condition `A[k]>A[i]`. If we cannot find anyone, it means that at this position there is a new start of increasing sequence, so we give `F[k]` a `1`.

After the loop, the results are well calculated and stored in the array `F`. So we can find the largest one and return it. It’s not very difficult, we can glance at the full code.

### Final Code

TO DO: There should be a solution with time complexity O(nlogn), find it out !