Lesson24 Enumeration
Lesson24 Enumeration
Question
Tony and Mary played a game using red and yellow two-color
pieces. Mary randomly arranged the two-color pieces in a
row, with some yellow sides up and some red sides up.
Tony needs to select a continuous section of two-color
pieces and flip each one, so that after one flip, the number
of red two-color pieces is maximized.
Can you help Tony figure out how many red two-color pieces
can be maximized in this game? (The number of two-color
pieces is less than 10.)
Question
Tony and Mary played a game using red and yellow two-color pieces. Mary
randomly arranged the two-color pieces in a row, with some yellow sides up and
some red sides up.
Tony needs to select a continuous section of two-color pieces and flip each one,
so that after one flip, the number of red two-color pieces is maximized. Can you
help Tony figure out how many red two-color pieces can be maximized in this
game? (The number of two-color pieces is less than 10.)
Example 1 Example 2
Flip Flip
2 red 4 red
Define the problem
n < 10
The state of a 2-color piece can be
Number of 2-color piece: <10 represented by the array colors of
Input Status of 2-color piece: Yellow length n
up or red up colors[i]: 0
1
Select a continuous strip of Select a start and an end (start
two-colored pieces <= end)
Operatio
n
Flip each piece in the selected Then invert all values in the range
strip (i.e., change red to yellow colors[start] to colors[end] (0 to
and yellow to red) 1,1 to 0)
By one flip operation, the Find a combination of start and end
Goal maximum number of two-color that flips the array colors with the
pieces with red up greatest number of 1s
ifcurrent_ones
_____________ >max_ones
_____________ , then update max_ones
Run time
(n) 2
1.5
5 0.0067108
1
50 0.0110654
s
0.5
100 0.0337362 0
5 50 100 500
500 2.673159
2-color pieces ( n )
Algorithm optimization
1.Orginal sufSum-
preSum interSum sufSum colors[end]
2.Orginal
colors 1 0 1 0 1 interSum+color
s[end]’s flip
3.Re-calculate the
start end
number of 1s in
array colors
Algorithm optimization
O(n3) O(n2) 3
2- 2.5
color Run time Run time
Run time
2
piece (s) (s)
s(n) 1.5
0.006710 0.001522 1
5
8 9
s
0.5
0.011065 0.002200
50
4 6 0
5 50 100 500
0.033736 0.003356
100
2 3 2-color pieces ( n )
0.046930
500 2.673159
5