John Doe crook fence consist n rectangular plank line leave right plank go ith 1 in leave right width 1 height hi we assume plank go ith 1 in left right index iA piece fence l r 1lrn sequence plank wood indice l r inclusive plank index ll1r the width piece fence l r value rl1two piece fence l1 r1 l2 r2 call matching follow condition hold piece intersect is not single plank occur piece fence piece width 0ir1l1 follow condition hold hl1ihl2ihl1hl2 John choose piece fence want know distinct matching piece two piece fence distinct plank belong belong