问题描述
给定一个序列,如Array[10,3,80,1,20,22,5,75,65,80]
,计算其中最大递增子序列长度。
问题分析
仍然应用动态规划算法思想,首先分解问题,使用MaxSubSeqLen[i]
标记第[i]
个元素之前的序列中最大递增子序列长度。然后分析递推规则,查找第[i]
个元素之前小于等于第[i]
个元素中已计算并缓存MaxSubSeqLen[x]
最大的一个,设置MaxSubSeqLen[i] = MaxSubSeqLen[x] + 1
。
算法实现
private static int calcMaxIncSubSeq(int p_samples[], int len)
{
int maxIncSubSeqLen = 0;
int maxIncSubSeqLenArray[] = new int[len];
maxIncSubSeqLenArray[0] = 1;
for (int i=1; i<len; i++)
{
calcMaxIncSubSeqAtCurrentPoint(p_samples, i, maxIncSubSeqLenArray);
maxIncSubSeqLen = compareAndSwap(maxIncSubSeqLen, maxIncSubSeqLenArray[i]);
}
return maxIncSubSeqLen;
}
private static void calcMaxIncSubSeqAtCurrentPoint(int[] p_samples, int p_index,
int[] p_maxIncSubSeqLenArray) {
for (int i=0; i<p_index; i++)
{
if (p_samples[i] <= p_samples[p_index])
{
p_maxIncSubSeqLenArray[p_index] = compareAndSwap(p_maxIncSubSeqLenArray[p_index], p_maxIncSubSeqLenArray[i]+1);
}
}
}
public static int compareAndSwap(int p_maxData, int p_candidateData)
{
if (p_maxData < p_candidateData)
{
p_maxData = p_candidateData;
}
return p_maxData;
}