NOTE: NOT must be start from the beginning, probably the longest start from the middle
(1,4)(2,3)(3,4)(5,6)
start from: (1,4)(5,6),
(2,3) unfit
start from: (2,3)(3,4)(5,6) , the longest
C 50 5' 5
A B
80 6' 70 5' 9
2. Implementation
Input (ht, wt)=(inch, lb): (65,100) (70,150) (56,90) (75,190) (60,95) (68,110)
Output: the longest tower: (56,90) ( 60,95) (65,100) (68,110) (70,150) (75,190)
1. sorted ht,wt
sort ht, if ht same, sort wt
check wt is larger than previous ht
public class Question
{
ArrayList items;
ArrayList lastFoundSeq;
ArrayList maxSeq;
// Returns longer sequence
ArrayList seqWithMaxLength(ArrayList seq1, ArrayList seq2)
{
return seq1.size() > seq2.size() ? seq1:seq2;
}
// Fills next seq w decreased wt & returns index of 1st unfit item
int fillNextSeq(int startFrom, ArrayList seq)
{
int fristUnfitItem = strartFrom;
int count = 0;
if ( startFrom < item.size() )
{
for ( int i = 0; i < items.size(); i++ )
{
HtWt item = items.get(i);
if ( i== 0 || items.get(i-1).isBefore(item) )
seq.add(item);
else
{
if (count == 0)
{
firstUnfitItem = i;
count++;
}
}
}
}
return firstUnfitItem;
}
// Find the maximum length of sequence
void findMaxSeq()
{
Collections.sort(items);
int currentUnfit = 0;
while (currentUnfit < items.size())
{
// NOTE: get New unfit index and New seq
ArrayList nextSeq = new ArrayList();
int nextUnfit = fillNextSeq(currentUnfit, nextSeq);
maxSeq = seqWithMaxLEngth(maxSeq, nextSeq);
//NOTE: new unfit index
if (nextUnfit == currentUnfit)
break;
else
currentUnfit = nextUnfit;
}
}
}
3. Similar Ones