数组最长递增子序列

#include<iostream>

int getLIS(int* a, int n)
{
	int* maxV = new int[n + 1];
	maxV[0] = INT_MIN;
	maxV[1] = a[0];

	for (int i = 2; i < n + 1; i++)
	{
		maxV[i] = INT_MAX;
	}

	int* LIS = new int[n];

	for (int i = 0; i < n; i++)
	{
		LIS[i] = 1;
	}

	int maxLIS = 1;

	for (int i = 1; i < n; i++)
	{
		//binary search
		int left = 0, right = maxLIS, mid;

		while (left <= right)
		{
			mid = (left + right) / 2;
			if (maxV[mid] <= a[i] && maxV[mid + 1] > a[i])
			{
				LIS[i] = mid + 1;
				break;
			}
			else if (maxV[mid] > a[i])
				right = mid - 1;
			else
				left = mid + 1;
		}

		if (LIS[i] > maxLIS)
		{
			maxLIS = LIS[i];
			maxV[LIS[i]] = a[i];
		}
		else if (maxV[mid] < a[i] && maxV[mid + 1] > a[i])
		{
			maxV[mid + 1] = a[i];
		}
	}

	return maxLIS;
};



int main()
{
	int a[] = {1, -1, 2, -3, 4, -5, 6, -7};
	int res = getLIS(a, 7);
	return 0;

}

你可能感兴趣的:(数组最长递增子序列)