Eating Together

Time limit1sMemory limit128 MB

Summary
Given a sequence of values from 1 to 3, find the fewest card changes so the sequence becomes non-decreasing or non-increasing.
Level

Easy3 of 10

Topics
Implementation, Brute force, Dynamic programming
Solved
No attempts yet

Problem

The cows are very particular about their dinner companions. They have split into three dining groups (numbered 1, 2, and 3 for convenience), and each group insists on eating together. When all NN cows (1≤N≤30 0001 \le N \le 30\,000) line up for feeding, however, they are not arranged by dining group.

Each cow ii carries a card engraved with a number DiD_i (1≤Di≤31 \le D_i \le 3) indicating her dining group.

Farmer John walks down the line and may change a cow's group by erasing the old number on her card and writing a new one. His goal is to make the group numbers, read along the line, sorted in either non-decreasing order (for example 111222333) or non-increasing order (for example 333222111). He may only change the numbers on the cards; he may not rearrange the cows in line.

Find the minimum number of cards he must change so that the final sequence of group numbers is sorted in either ascending or descending order.

Input

  • Line 1: an integer NN.
  • Lines 2 through N+1N+1: line i+1i+1 contains a single integer DiD_i, the current dining group of the ii-th cow.

Output

  • A single integer: the minimum number of changes needed so that the final sequence is sorted in either non-decreasing or non-increasing order.

Examples1

  1. Example 1

    Input
    5
    1
    3
    2
    1
    1
    
    Expected output
    1