SlideShare a Scribd company logo
Algorithms
Practice &
Problem Solving
Women Who Code
Meet the Organizers
Xochitl Watts
Twitter: @XochitlWatts
https://www.a2omini.com
Kelly KappJennifer Sweezey
What are algorithms?
(In mathematics, computing, and related subjects) An algorithm is an
effective method for solving a problem using a finite sequence of actions to be
performed.
- Wikipedia
Essentials to Solving a Problem
A data structure holds data and allows a specific set of operations to be
performed on a data set.
Data Structures
1) Record
2) Linked List
3) Stack
4) Queue
5) Set
6) Map
7) Graph
8) Tree
9) Heaps
Algorithm Design
1) Divide and Conquer
2) Greedy Method
3) Dynamic Programming
4) Graph traversal methods
5) Branch and Bound
Dynamic Programming (DP)
1) DP builds its solution by constructing solutions to smaller instances of the
same problem.
2) A problem has an optimal substructure if the sub-solutions of an optimal
solution of the problem are optimal solutions for their sub-problems.
3) The problem contains overlapping sub-problems.
4) DP arrives to a solution using bottom up traversal, building the solution to
many sub-problems that may or may not be required.
Memoize & re-use solutions to subproblems that help solve the problem
Example: Compute n-th Fibonacci number
Recursion
function fib(int n) {
If (n <= 2) {
return 1;
}
return fib(n-1) + fib(n-2);
}
Dynamic Programming
long a[] = new long[n + 1];
a[1] = a[2] = 1
for (int i=3; i <=n; i++) {
a[i] = a[i-1] + a[i-2];
}
return a[n];
Memoization
Memoization aims to prevent recomputations by storing (memorizing) the
return values of the function calls.
http://en.wikipedia.org/wiki/Memoization
Example: Compute n-th Fibonacci number
Recursion Dynamic Programming
n Time (MSEC)
10 0
20 1
30 8
40 922
50 113770
n Time (MSEC)
10 0
20 0
30 0
40 0
50 0
DP Template - NORA
1) Notation: Develop a mathematical notation that can express any solution
and any sub-solution for the problem at hand.
2) Optimality: Prove that the optimal substructure holds - sub-solutions of
an optimal solution are optimal solutions for sub-problems.
3) Recurrence: Develop a recurrence relation that relates a solution to its
sub-solutions using math notation.
4) Algorithm: Write out the algorithm, iterate over all the parameters of the
recurrence relation to compute the results for the actual problem that
needed to be solved.
Fibonacci Finding Challenge
https://www.hackerrank.com/challenges/fibonacci-finding-easy
Coin Change Challenge
https://www.hackerrank.com/challenges/coin-change
Python Solution: Fibonacci Finding Challenge
def fibonacci(n):
if n < 2:
return n
if not n in memory.keys():
memory[n] = fibonacci(n-1) + fibonacci(n-2)
return memory[n]
memory = {}
n = int(raw_input())
print(fibonacci(n))
Python Solution: Coin Change Challenge
Recursion
def count(sum_, coins):
if len(coins) == 0:
return 0
if sum_ < 0:
return 0
if sum_ == 0:
return 1
return count(sum_ - coins[0], coins) + count(sum_, coins[1:])
if __name__ == "__main__":
import sys
N, M = map(int, sys.stdin.readline().strip().split(' '))
coins = map(int, sys.stdin.readline().strip().split(' '))
print count(N, coins)
Python Solution: Coin Change Challenge
Memoization
count_dict = {}
def count(sum_, coins):
if len(coins) == 0:
return 0
if sum_ < 0:
return 0
if sum_ == 0:
return 1
key = (sum_, tuple(coins))
if key not in count_dict:
count_dict[key] = count(sum_ - coins[0], coins) + count(sum_, coins[1:])
return count_dict[key]
if __name__ == "__main__":
import sys
N, M = map(int, sys.stdin.readline().strip().split(' '))
coins = map(int, sys.stdin.readline().strip().split(' '))
print count(N, coins)
Python Solution: Coin Change Challenge
Dynamic Programming
def count(N, coins):
numWays = [[1] + N * [0] for j in xrange(len(coins) + 1)]
for i in xrange(1, len(coins) + 1):
for j in xrange(1, N + 1):
numWays[i][j] = numWays[i-1][j] + (numWays[i][j - coins[i-1]]
if coins[i-1] <= j else 0)
return numWays[-1][-1]
if __name__ == "__main__":
import sys
N, M = map(int, sys.stdin.readline().strip().split(' '))
coins = map(int, sys.stdin.readline().strip().split(' '))
print count(N, coins)
Reference
Analysis and Design of Algorithms - It takes 4 hours to read the whole book.

More Related Content

What's hot (20)

PPTX
Dynamic Programming
paramalways
 
PPTX
Applications of numerical methods
Daffodil International University
 
PDF
Sol1
berhe1
 
PDF
Backtracking based integer factorisation, primality testing and square root c...
csandit
 
PDF
Introduction to conventional machine learning techniques
Xavier Rafael Palou
 
PDF
Derivation of Convolutional Neural Network (ConvNet) from Fully Connected Net...
Ahmed Gad
 
PPTX
Binary Class and Multi Class Strategies for Machine Learning
Paxcel Technologies
 
PDF
Linear Algebra – A Powerful Tool for Data Science
Premier Publishers
 
PDF
A01
lksoo
 
PPT
Problem solving
hamza239523
 
PDF
Classification case study + intro to cnn
Vincent Tatan
 
PPTX
Using sage maths to solve systems of linear equations
Robert Geofroy
 
PPTX
Learning multifractal structure in large networks (Purdue ML Seminar)
Austin Benson
 
PDF
MATLAB Code + Description : Real-Time Object Motion Detection and Tracking
Ahmed Gad
 
PPTX
Algorithm and Data Structures - Basic of IT Problem Solving
coolpie
 
PDF
00 - 30 Dec - Introduction
Neeldhara Misra
 
PDF
07 dimensionality reduction
Marco Quartulli
 
PDF
A tour of the top 10 algorithms for machine learning newbies
Vimal Gupta
 
PPTX
Curse of dimensionality
Nikhil Sharma
 
PDF
Probability And Stats Intro2
mailund
 
Dynamic Programming
paramalways
 
Applications of numerical methods
Daffodil International University
 
Sol1
berhe1
 
Backtracking based integer factorisation, primality testing and square root c...
csandit
 
Introduction to conventional machine learning techniques
Xavier Rafael Palou
 
Derivation of Convolutional Neural Network (ConvNet) from Fully Connected Net...
Ahmed Gad
 
Binary Class and Multi Class Strategies for Machine Learning
Paxcel Technologies
 
Linear Algebra – A Powerful Tool for Data Science
Premier Publishers
 
A01
lksoo
 
Problem solving
hamza239523
 
Classification case study + intro to cnn
Vincent Tatan
 
Using sage maths to solve systems of linear equations
Robert Geofroy
 
Learning multifractal structure in large networks (Purdue ML Seminar)
Austin Benson
 
MATLAB Code + Description : Real-Time Object Motion Detection and Tracking
Ahmed Gad
 
Algorithm and Data Structures - Basic of IT Problem Solving
coolpie
 
00 - 30 Dec - Introduction
Neeldhara Misra
 
07 dimensionality reduction
Marco Quartulli
 
A tour of the top 10 algorithms for machine learning newbies
Vimal Gupta
 
Curse of dimensionality
Nikhil Sharma
 
Probability And Stats Intro2
mailund
 

Viewers also liked (19)

PPTX
Dynamic Programming
Sahil Kumar
 
PDF
11 - 03 Feb - From Recursion to Dynamic Programming
Neeldhara Misra
 
PDF
Numerical analysis m5 l2slides
SHAMJITH KM
 
PDF
Better Open Source Enterprise C++ Web Services
WSO2
 
PDF
Milot Shala - C++ (OSCAL2014)
Open Labs Albania
 
PPTX
Static analysis of C++ source code
Andrey Karpov
 
TXT
Fibonacci surce code
German Niebles
 
PDF
Tora (2 phase itteration, simplex method)
Zeeshan Mirza
 
PDF
2. lp iterative methods
Hakeem-Ur- Rehman
 
PPTX
LINEAR PROGRAMMING Assignment help
john mayer
 
PPT
Artificial variable technique big m method (1)
ਮਿਲਨਪ੍ਰੀਤ ਔਜਲਾ
 
PPTX
Two Phase Method- Linear Programming
Manas Lad
 
PPTX
Big m method
Luckshay Batra
 
PPT
5.3 dynamic programming 03
Krish_ver2
 
PPTX
Dynamic Programming-Knapsack Problem
Amrita Yadav
 
PPT
Lecture 8 dynamic programming
Oye Tu
 
PPTX
dynamic programming complete by Mumtaz Ali (03154103173)
Mumtaz Ali
 
PPT
Simplex two phase
Shakti Ranjan
 
PDF
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
Dynamic Programming
Sahil Kumar
 
11 - 03 Feb - From Recursion to Dynamic Programming
Neeldhara Misra
 
Numerical analysis m5 l2slides
SHAMJITH KM
 
Better Open Source Enterprise C++ Web Services
WSO2
 
Milot Shala - C++ (OSCAL2014)
Open Labs Albania
 
Static analysis of C++ source code
Andrey Karpov
 
Fibonacci surce code
German Niebles
 
Tora (2 phase itteration, simplex method)
Zeeshan Mirza
 
2. lp iterative methods
Hakeem-Ur- Rehman
 
LINEAR PROGRAMMING Assignment help
john mayer
 
Artificial variable technique big m method (1)
ਮਿਲਨਪ੍ਰੀਤ ਔਜਲਾ
 
Two Phase Method- Linear Programming
Manas Lad
 
Big m method
Luckshay Batra
 
5.3 dynamic programming 03
Krish_ver2
 
Dynamic Programming-Knapsack Problem
Amrita Yadav
 
Lecture 8 dynamic programming
Oye Tu
 
dynamic programming complete by Mumtaz Ali (03154103173)
Mumtaz Ali
 
Simplex two phase
Shakti Ranjan
 
How to Become a Thought Leader in Your Niche
Leslie Samuel
 
Ad

Similar to Algorithms practice and problem solving - dynamic programming (20)

PDF
Dynamic programing
AniketSingh609353
 
PPT
Chap08alg
Munkhchimeg
 
PPT
Chap08alg
Munhchimeg
 
PDF
DS & Algo 6 - Dynamic Programming
Mohammad Imam Hossain
 
PPTX
Annotaed slides for dynamic programming algorithm
johnathangamal27
 
PPTX
Introduction to Dynamic Programming.pptx
PochupouOwo
 
PPT
Dynamic pgmming
Dr. C.V. Suresh Babu
 
PPT
Dynamicpgmming
Muhammad Wasif
 
PPTX
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
Simplilearn
 
PPTX
Dynamic Programming.pptx
MuktarHossain13
 
PPTX
DynamicProgramming.pptx
SaimaShaheen14
 
PPTX
Types of algorithms
Amelita Martinez
 
PPT
35 algorithm-types
ashish bansal
 
PPT
algorithm-types.ppt
TusharSharma759024
 
PPT
35-algorithm-types.ppt
HarikumarRajandran1
 
PPT
35 algorithm-types
EducationalJunction
 
PPT
35 algorithm-types
Kislay Bhardwaj L|PT,ECSA,C|EH
 
PPTX
Cracking the Facebook Coding Interview.pptx
SergiuBrsa
 
PPTX
5617723.pptx
MatthewMhlongo
 
PPT
Algorithm types
JavariaIbrahim
 
Dynamic programing
AniketSingh609353
 
Chap08alg
Munkhchimeg
 
Chap08alg
Munhchimeg
 
DS & Algo 6 - Dynamic Programming
Mohammad Imam Hossain
 
Annotaed slides for dynamic programming algorithm
johnathangamal27
 
Introduction to Dynamic Programming.pptx
PochupouOwo
 
Dynamic pgmming
Dr. C.V. Suresh Babu
 
Dynamicpgmming
Muhammad Wasif
 
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
Simplilearn
 
Dynamic Programming.pptx
MuktarHossain13
 
DynamicProgramming.pptx
SaimaShaheen14
 
Types of algorithms
Amelita Martinez
 
35 algorithm-types
ashish bansal
 
algorithm-types.ppt
TusharSharma759024
 
35-algorithm-types.ppt
HarikumarRajandran1
 
35 algorithm-types
EducationalJunction
 
35 algorithm-types
Kislay Bhardwaj L|PT,ECSA,C|EH
 
Cracking the Facebook Coding Interview.pptx
SergiuBrsa
 
5617723.pptx
MatthewMhlongo
 
Algorithm types
JavariaIbrahim
 
Ad

Recently uploaded (20)

PDF
Informatics Market Insights AI Workforce.pdf
karizaroxx
 
PDF
SaleServicereport and SaleServicereport
2251330007
 
PDF
GOOGLE ADS (1).pdf THE ULTIMATE GUIDE TO
kushalkeshwanisou
 
PPTX
Mynd company all details what they are doing a
AniketKadam40952
 
PDF
CT-2-Ancient ancient accept-Criticism.pdf
DepartmentofEnglishC1
 
PPTX
MENU-DRIVEN PROGRAM ON ARUNACHAL PRADESH.pptx
manvi200807
 
DOCX
COT Feb 19, 2025 DLLgvbbnnjjjjjj_Digestive System and its Functions_PISA_CBA....
kayemorales1105
 
PDF
TESDA License NC II PC Operations TESDA, Office Productivity
MELJUN CORTES
 
PPTX
RESEARCH-FINAL-GROUP-3, about the final .pptx
gwapokoha1
 
PPTX
Daily, Weekly, Monthly Report MTC March 2025.pptx
PanjiDewaPamungkas1
 
PPT
Reliability Monitoring of Aircrfat commerce
Rizk2
 
PPTX
microservices-with-container-apps-dapr.pptx
vjay22
 
PDF
Kafka Use Cases Real-World Applications
Accentfuture
 
PDF
TCU EVALUATION FACULTY TCU Taguig City 1st Semester 2017-2018
MELJUN CORTES
 
PPTX
727325165-Unit-1-Data-Analytics-PPT-1.pptx
revathi148366
 
PDF
Business Automation Solution with Excel 1.1.pdf
Vivek Kedia
 
PPTX
Project_Update_Summary.for the use from PM
Odysseas Lekatsas
 
DOCX
brigada_PROGRAM_25.docx the boys white house
RonelNebrao
 
PDF
IT GOVERNANCE 4-2 - Information System Security (1).pdf
mdirfanuddin1322
 
PDF
A Web Repository System for Data Mining in Drug Discovery
IJDKP
 
Informatics Market Insights AI Workforce.pdf
karizaroxx
 
SaleServicereport and SaleServicereport
2251330007
 
GOOGLE ADS (1).pdf THE ULTIMATE GUIDE TO
kushalkeshwanisou
 
Mynd company all details what they are doing a
AniketKadam40952
 
CT-2-Ancient ancient accept-Criticism.pdf
DepartmentofEnglishC1
 
MENU-DRIVEN PROGRAM ON ARUNACHAL PRADESH.pptx
manvi200807
 
COT Feb 19, 2025 DLLgvbbnnjjjjjj_Digestive System and its Functions_PISA_CBA....
kayemorales1105
 
TESDA License NC II PC Operations TESDA, Office Productivity
MELJUN CORTES
 
RESEARCH-FINAL-GROUP-3, about the final .pptx
gwapokoha1
 
Daily, Weekly, Monthly Report MTC March 2025.pptx
PanjiDewaPamungkas1
 
Reliability Monitoring of Aircrfat commerce
Rizk2
 
microservices-with-container-apps-dapr.pptx
vjay22
 
Kafka Use Cases Real-World Applications
Accentfuture
 
TCU EVALUATION FACULTY TCU Taguig City 1st Semester 2017-2018
MELJUN CORTES
 
727325165-Unit-1-Data-Analytics-PPT-1.pptx
revathi148366
 
Business Automation Solution with Excel 1.1.pdf
Vivek Kedia
 
Project_Update_Summary.for the use from PM
Odysseas Lekatsas
 
brigada_PROGRAM_25.docx the boys white house
RonelNebrao
 
IT GOVERNANCE 4-2 - Information System Security (1).pdf
mdirfanuddin1322
 
A Web Repository System for Data Mining in Drug Discovery
IJDKP
 

Algorithms practice and problem solving - dynamic programming

  • 2. Meet the Organizers Xochitl Watts Twitter: @XochitlWatts https://www.a2omini.com Kelly KappJennifer Sweezey
  • 3. What are algorithms? (In mathematics, computing, and related subjects) An algorithm is an effective method for solving a problem using a finite sequence of actions to be performed. - Wikipedia
  • 4. Essentials to Solving a Problem A data structure holds data and allows a specific set of operations to be performed on a data set. Data Structures 1) Record 2) Linked List 3) Stack 4) Queue 5) Set 6) Map 7) Graph 8) Tree 9) Heaps Algorithm Design 1) Divide and Conquer 2) Greedy Method 3) Dynamic Programming 4) Graph traversal methods 5) Branch and Bound
  • 5. Dynamic Programming (DP) 1) DP builds its solution by constructing solutions to smaller instances of the same problem. 2) A problem has an optimal substructure if the sub-solutions of an optimal solution of the problem are optimal solutions for their sub-problems. 3) The problem contains overlapping sub-problems. 4) DP arrives to a solution using bottom up traversal, building the solution to many sub-problems that may or may not be required. Memoize & re-use solutions to subproblems that help solve the problem
  • 6. Example: Compute n-th Fibonacci number Recursion function fib(int n) { If (n <= 2) { return 1; } return fib(n-1) + fib(n-2); } Dynamic Programming long a[] = new long[n + 1]; a[1] = a[2] = 1 for (int i=3; i <=n; i++) { a[i] = a[i-1] + a[i-2]; } return a[n];
  • 7. Memoization Memoization aims to prevent recomputations by storing (memorizing) the return values of the function calls. http://en.wikipedia.org/wiki/Memoization
  • 8. Example: Compute n-th Fibonacci number Recursion Dynamic Programming n Time (MSEC) 10 0 20 1 30 8 40 922 50 113770 n Time (MSEC) 10 0 20 0 30 0 40 0 50 0
  • 9. DP Template - NORA 1) Notation: Develop a mathematical notation that can express any solution and any sub-solution for the problem at hand. 2) Optimality: Prove that the optimal substructure holds - sub-solutions of an optimal solution are optimal solutions for sub-problems. 3) Recurrence: Develop a recurrence relation that relates a solution to its sub-solutions using math notation. 4) Algorithm: Write out the algorithm, iterate over all the parameters of the recurrence relation to compute the results for the actual problem that needed to be solved.
  • 12. Python Solution: Fibonacci Finding Challenge def fibonacci(n): if n < 2: return n if not n in memory.keys(): memory[n] = fibonacci(n-1) + fibonacci(n-2) return memory[n] memory = {} n = int(raw_input()) print(fibonacci(n))
  • 13. Python Solution: Coin Change Challenge Recursion def count(sum_, coins): if len(coins) == 0: return 0 if sum_ < 0: return 0 if sum_ == 0: return 1 return count(sum_ - coins[0], coins) + count(sum_, coins[1:]) if __name__ == "__main__": import sys N, M = map(int, sys.stdin.readline().strip().split(' ')) coins = map(int, sys.stdin.readline().strip().split(' ')) print count(N, coins)
  • 14. Python Solution: Coin Change Challenge Memoization count_dict = {} def count(sum_, coins): if len(coins) == 0: return 0 if sum_ < 0: return 0 if sum_ == 0: return 1 key = (sum_, tuple(coins)) if key not in count_dict: count_dict[key] = count(sum_ - coins[0], coins) + count(sum_, coins[1:]) return count_dict[key] if __name__ == "__main__": import sys N, M = map(int, sys.stdin.readline().strip().split(' ')) coins = map(int, sys.stdin.readline().strip().split(' ')) print count(N, coins)
  • 15. Python Solution: Coin Change Challenge Dynamic Programming def count(N, coins): numWays = [[1] + N * [0] for j in xrange(len(coins) + 1)] for i in xrange(1, len(coins) + 1): for j in xrange(1, N + 1): numWays[i][j] = numWays[i-1][j] + (numWays[i][j - coins[i-1]] if coins[i-1] <= j else 0) return numWays[-1][-1] if __name__ == "__main__": import sys N, M = map(int, sys.stdin.readline().strip().split(' ')) coins = map(int, sys.stdin.readline().strip().split(' ')) print count(N, coins)
  • 16. Reference Analysis and Design of Algorithms - It takes 4 hours to read the whole book.