Lec 09
Lec 09
of Algorithms
Lecture 9
Keerti Choudhary
Department of CSE, IIT Delhi
Dynamic Programming
using
Efficient Data-Structures
Mario Game
7
Each brick has
exactly one coin 6
4 4
3 3 3
2 2
An optimal
jump sequence 7
Each brick has
exactly one coin 6
4 4
3 3 3
2 2
Question:
What should be the
sub-problems,
and how to solve them?
Longest Increasing Subsequence
Ans. No! This will not work for array A = [7, 8, 9, 1, 2, 3, 4, 5, 6].
Longest Increasing Subsequence
Ans. Yes!
Longest Increasing Subsequence
Sub-problem
LIS[i] = Length of LIS of A[0,i] terminating at ai.
Recurrence
LIS[i] = 1 + max {LIS[ j] xj < xi, and j ∈ [1,i − 1]}
Longest Increasing Subsequence
Sub-problem
LIS[i] = Length of LIS of A[0,i] terminating at ai.
Recurrence
LIS[i] = 1 + max {LIS[ j] aj < ai, and j ∈ [0, i − 1]}
Longest Increasing Subsequence
Sub-problem
LIS[i] = Length of LIS of A[0,i] terminating at ai.
Recurrence
LIS[i] = 1 + max {LIS[ j] aj < ai, and j ∈ [0, i − 1]}
2 Question:
Time complexity: O(n )
How to improve this?
Data-Structure
Problem
Data Structure Problem
1 2 3 4 5 6 7 8
Data Structure Problem
1 2 3 4 5 6 7 8
Dynamic: Towers are built in cities in an arbitrary order, with one tower per city.
Data Structure Problem
1 2 3 4 5 6 7 8
h = 400
Dynamic: Towers are built in cities in an arbitrary order, with one tower per city.
Data Structure Problem
1 2 3 4 5 6 7 8
h = 400 h = 800
Dynamic: Towers are built in cities in an arbitrary order, with one tower per city.
Data Structure Problem
1 2 3 4 5 6 7 8
h = 400 h = 800
Dynamic: Towers are built in cities in an arbitrary order, with one tower per city.
1 2 3 4 5 6 7 8
Data Structure Problem
[1-8]
[1-4] [5-8]
1 2 3 4 5 6 7 8
Data Structure Problem
Segment
[1-8]
Tree data-
structure
[1-4] [5-8]
1 2 3 4 5 6 7 8
400 800
400 800
400 800
[1-4] [5-8]
[1-4] [5-8]
[1-4] [5-8]
Ans: O(log n)
Data Structure Problem
[1-8]
[1-4] [5-8]
[1-4]
[5-6]
[1-4]
[5-6]
A = [8, 5, 7, 3, 9, 4, 11, 2]
A = [8, 5, 7, 3, 9, 4, 11, 2]
LIS[i]
Sorted A: A[7] A[3] A[5] A[1] A[2] A[0] A[4] A[6]
2 3 4 5 7 8 9 11
Sub-problem
A = [8, 5, 7, 3, 9, 4, 11, 2]
LIS[i] 1
A = [8, 5, 7, 3, 9, 4, 11, 2]
LIS[i] 1 1
A = [8, 5, 7, 3, 9, 4, 11, 2]
LIS[i] 1 2 1
A = [8, 5, 7, 3, 9, 4, 11, 2]
LIS[i] 1 1 2 1
A = [8, 5, 7, 3, 9, 4, 11, 2]
LIS[i] 1 1 2 1 3
A = [8, 5, 7, 3, 9, 4, 11, 2]
LIS[i] 1 ?? 1 2 1 3
LIS[5] = _____________
Sub-problem
A = [8, 5, 7, 3, 9, 4, 11, 2]
LIS[i] 1 ?? 1 2 1 3
A = [8, 5, 7, 3, 9, 4, 11, 2]
LIS[i] 1 ?? 1 2 1 3
A = [8, 5, 7, 3, 9, 4, 11, 2]
LIS[i] 1 ?? 1 2 1 3
Can you design an e cient algorithm for the Mario Coin collection game, for the
scenario where the bricks contain coins of varying values?
Can you design an O(n log n) time algorithm for Question 4 of Tutorial sheet 5.
ffi