Longest Increasing Subsequence in an Array

Given an array of integers, this algorithm finds the length of the longest increasing subsequence in the array. For example, given the input [10, 9, 2, 5, 3, 7, 101, 18], the output would be 4.

Problem

Given an array of integers, find the length of the longest increasing subsequence in the array.
Example input: [10, 9, 2, 5, 3, 7, 101, 18]
Example output: 4

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    vector<int> input = {10, 9, 2, 5, 3, 7, 101, 18};
    vector<int> dp(input.size(), 1);
    int max_len = 1;
    for (int i = 1; i < input.size(); i++) {
        for (int j = 0; j < i; j++) {
            if (input[i] > input[j]) {
                dp[i] = max(dp[i], dp[j] + 1);
            }
        }
        max_len = max(max_len, dp[i]);
    }
    cout << max_len << endl;
    return 0;
}

/*

The solution is optimal because it uses dynamic programming to solve the problem.

The solution is O(n^2) because it uses two for loops.

*/

A.I. Evaluation of the Solution

The candidate's solution is correct and uses dynamic programming to solve the problem. However, the solution is not very efficient because it uses two for loops.

Evaluated at: 2022-11-19 16:15:53