SlideShare a Scribd company logo
1 of 18
Download to read offline
The Candy Distribution Problem
Dynamic programming
15Z403 - Design and Analysis of Algorithms
PROBLEM
STATEMENT
Alice is a kindergarten teacher. She wants to give some candies
to the children in her class. All the children sit in a line and
each of them has a rating score according to his or her
performance in the class. Alice wants to give at least 1 candy to
each child. If two children sit next to each other, then the one
with the higher rating must get more candies. Alice wants to
minimize the total number of candies she must buy.
This above problem is to be solved using Dynamic Programming.
2
Design Technique Used
Dynamic Programming
Dynamic Programming is an algorithmic paradigm that solves a given complex
problem by breaking it into subproblems and stores the results of subproblems to
avoid computing the same results again.
3
“Dynamic programming is applicable to our problem as it has the following properties :
(Optimisation and Overlapping sub-problems)
• It can be partitioned into subproblems.
• Subproblems can be solved independently,
• Solutions (optimal) of the subproblems can be combined to (optimal) solutions of the
original problem.
• Subproblems have the same property (or are trivial).
4
How dynamic
programming is
used?
1. In Dynamic Programming questions, we are asked to calculate F[i] for some i. Here, F[i] is
the number of candies given to child i. (Then we sum the values.) The complexity is that the
value F[i] depends on other values, in this case for values of i both smaller and larger.
2. We are calculating candies[i] (number of candies given to child i) in an order such that the
“dependencies” (number of candies given to the child-i’s neighbours) for a given value i have
already been calculated. (Tabulation).
3. Problem is split into further subproblems whenever duplicates are found in consecutive
locations.
Example : ratings = [ 2 3 4 5 2 2 7 8 ]
It is divided into 2 sub problems as
• [ 2 3 4 5 2 ]
• [ 2 7 8 ]
And their optimal sub-solutions are combined to get optimal solution. (Minimum number of
candies).
5
N - Number of children.
ratings[1:N] - Array that contains ratings of N children.
candy_count - Contains the minimum number of candies.
is_min(ratings, j) - Checks if the element at position j is a local minimum.
is_max(ratings, j) - Checks if the element at position j is a local maximum.
find_next_min(ratings, i) - Finds the next local minimum after position i.
find_next_max(ratings, i) - Finds the next local maximum after position i.
Algorithm Candies :
6
Begin
1. Read N.
2. Set prev_repeat = 0, candy_count = 0.
3. Read ratings of n children one by one
2.1 If there are consecutive duplicates, at position i-1, i :
2.2.1 call num_candies(ratings[prev_repeat: i])
2.2.2 prev_repeat = i
4. candy_count = candy_count + num_candies(ratings[prev_repeat: n])
End
Algorithm Candies :
7
1. If number of children = 1, then return 1.
2. Initialize candies[] to zero (all N values).
3. Find first min (next_min) and set candies to 1
4. If the first element is a max, (not a min)
4.1 Iterate from next_min to 0 in reverse
4.1.1 set candies[i] = candies[i+1] + 1
5. Set prev_min = next_min and find new next_min and next_max.
Algorithm num_candies(ratings):
8
6. While there is still another min and another max
6.1 candies[next_min] = 1
6.2 Iterate from prev_min to next_max in steps of 1
6.2.1 candies[i] = candies[i - 1] + 1
6.3 Iterate from next_min to next_max in steps of -1
6.3.1 candies[i] = candies[i + 1] + 1
6.4 candies[next_max] = max(candies[next_max - 1], candies[next_max + 1]) + 1
6.5 Same as Step 5
7. If next_max is the last element
7.1 Iterate from prev_min to next_max in steps of -1
7.1.1 candies[i] = candies[i - 1] + 1
7.1.2 candies[next_max] = candies[next_max - 1] + 1
8. return sum of candies[]
Algorithm num_candies(ratings)
9
Ratings[i] 3 5 Ratings[i] 5 1 9 10 7 8
Candies[i] 0 0 Candies[i] 0 0 0 0 0 0
By Step 3 1 0 By Step 3 0 1 0 0 0 0
By Step 7 1 2 By Step 4 2 1 0 0 0 0
By Step 6.1 2 1 0 0 1 0
By Step 6.2 2 1 2 0 1 0
By Step 6.4 2 1 2 3 1 0
By Step 7 2 1 2 3 1 2
Sum = 3 Sum = 11
Sum = 3+11 = 14
Tracing
def is_min(ratings, j):
# Checks if the element at position j is a local minimum
if j == 0:
return ratings[0] < ratings[1]
elif j == len(ratings) - 1:
return ratings[j - 1] > ratings[j]
else:
return ratings[j - 1] > ratings[j] and ratings[j] < ratings[j + 1]
def is_max(ratings, j):
# Checks if the element at position j is a local maximum
if j == 0:
return ratings[0] > ratings[1]
elif j == len(ratings) - 1:
return ratings[j - 1] < ratings[j]
else:
return ratings[j - 1] < ratings[j] and ratings[j] > ratings[j + 1]
Source Code - Implementation using Python 3
11
def find_next_min(ratings, i):
# Finds the next local minimum after position i
if i == None:
return None
for j in range(i + 1, len(ratings)):
if is_min(ratings, j):
return j
return None
def find_next_max(ratings, i):
# Finds the next local maximum after position i
if i == None:
return None
for j in range(i + 1, len(ratings)):
if is_max(ratings, j):
return j
return None
Source Code
12
def num_candies(ratings):
if len(ratings) == 1:
return 1
candies = [0]*len(ratings)
# Find first min and set candies to 1
next_min = find_next_min(ratings, -1)
candies[next_min] = 1
# If the first element is a max, not a min
if next_min != 0:
for i in range(next_min - 1, -1, -1):
candies[i] = candies[i + 1] + 1
# Find next min and max
prev_min = next_min
next_max = find_next_max(ratings, prev_min) # next_max after prev_min
next_min = find_next_min(ratings, next_max) # next_min after next_max
Source Code
13
# While there is still another min and another max
while next_min and next_max:
candies[next_min] = 1
# Iterate inward from mins to max
for i in range(prev_min + 1, next_max):
candies[i] = candies[i - 1] + 1
for i in range(next_min - 1, next_max, -1):
candies[i] = candies[i + 1] + 1
# Set candies of max
candies[next_max] = max(candies[next_max - 1], candies[next_max + 1]) + 1
Source Code
14
# If next_max is the last element
if next_max:
for i in range(prev_min + 1, next_max):
candies[i] = candies[i - 1] + 1
candies[next_max] = candies[next_max - 1] + 1
return sum(candies)
# Main Program
N = int(input())
ratings = [int(input())]
candy_count = 0
prev_repeat = 0
for i in range(1, N):
ratings.append(int(input()))
if ratings[i] == ratings[i - 1]:
candy_count += num_candies(ratings[prev_repeat: i])
prev_repeat = i
candy_count += num_candies(ratings[prev_repeat:])
print(candy_count)
Source Code
15
Output - Minimum number of Candies
16
Output - (i)
Output - (ii)
O(n)
Time Complexity
In the num_candies function, the each of the loops run not more than n times in the worst
case, (where n is the number of children) and hence the time taken is linear.
17
Thanks!
Presentation by
Preethi S V (17z231)
Sivakami N (17z245)
Varsha Devi K (17z256)
Samyuktha G (17z238)
Tejaswini Sivakumar (17z253)
18

More Related Content

What's hot

Andaman Nicobar Tour Package
Andaman Nicobar Tour PackageAndaman Nicobar Tour Package
Andaman Nicobar Tour PackageAnnu Tanya Singh
 
West bengal tourism prospective as per report published
West bengal tourism prospective as per report publishedWest bengal tourism prospective as per report published
West bengal tourism prospective as per report publishedGurmukh Jethwani
 
Ahmedabad,The Metropolitan city
Ahmedabad,The Metropolitan cityAhmedabad,The Metropolitan city
Ahmedabad,The Metropolitan cityHimanshu Pipaliya
 
Ppt on himachal pradesh
Ppt on himachal pradeshPpt on himachal pradesh
Ppt on himachal pradeshkitturashmikittu
 
Surat ~ the city of sun
Surat ~ the city of sunSurat ~ the city of sun
Surat ~ the city of sunMAYUR BEHERA
 
Andaman & nicobar islands
Andaman & nicobar islandsAndaman & nicobar islands
Andaman & nicobar islandsBHASKAR SAILESH
 
Aamchi mumbai ppt
Aamchi mumbai pptAamchi mumbai ppt
Aamchi mumbai pptTani305
 
Contemporary Cricket Quiz - Celebrating return of cricket after Covid-19
Contemporary Cricket Quiz - Celebrating return of cricket after Covid-19Contemporary Cricket Quiz - Celebrating return of cricket after Covid-19
Contemporary Cricket Quiz - Celebrating return of cricket after Covid-19Sajith Krishna
 
Agraharams The Origin And Evolution Of A Unique Housing Pattern In Kerala
Agraharams  The Origin And Evolution Of A Unique Housing Pattern In KeralaAgraharams  The Origin And Evolution Of A Unique Housing Pattern In Kerala
Agraharams The Origin And Evolution Of A Unique Housing Pattern In KeralaErica Thompson
 
Geography of india
Geography of indiaGeography of india
Geography of indiaAbhishek Sharma
 

What's hot (20)

Satyam Fiasco
Satyam FiascoSatyam Fiasco
Satyam Fiasco
 
Andaman Nicobar Tour Package
Andaman Nicobar Tour PackageAndaman Nicobar Tour Package
Andaman Nicobar Tour Package
 
Manali
ManaliManali
Manali
 
India Quiz
India QuizIndia Quiz
India Quiz
 
West bengal tourism prospective as per report published
West bengal tourism prospective as per report publishedWest bengal tourism prospective as per report published
West bengal tourism prospective as per report published
 
Ahmedabad,The Metropolitan city
Ahmedabad,The Metropolitan cityAhmedabad,The Metropolitan city
Ahmedabad,The Metropolitan city
 
Assam ppt
Assam     pptAssam     ppt
Assam ppt
 
Indian Travelogue-Ujjain
Indian Travelogue-Ujjain Indian Travelogue-Ujjain
Indian Travelogue-Ujjain
 
Ppt on himachal pradesh
Ppt on himachal pradeshPpt on himachal pradesh
Ppt on himachal pradesh
 
Surat ~ the city of sun
Surat ~ the city of sunSurat ~ the city of sun
Surat ~ the city of sun
 
Qutub minar
Qutub minarQutub minar
Qutub minar
 
Assam
AssamAssam
Assam
 
Andaman & nicobar islands
Andaman & nicobar islandsAndaman & nicobar islands
Andaman & nicobar islands
 
Aamchi mumbai ppt
Aamchi mumbai pptAamchi mumbai ppt
Aamchi mumbai ppt
 
Shimla
ShimlaShimla
Shimla
 
Contemporary Cricket Quiz - Celebrating return of cricket after Covid-19
Contemporary Cricket Quiz - Celebrating return of cricket after Covid-19Contemporary Cricket Quiz - Celebrating return of cricket after Covid-19
Contemporary Cricket Quiz - Celebrating return of cricket after Covid-19
 
Qutub Minar
Qutub  MinarQutub  Minar
Qutub Minar
 
Agraharams The Origin And Evolution Of A Unique Housing Pattern In Kerala
Agraharams  The Origin And Evolution Of A Unique Housing Pattern In KeralaAgraharams  The Origin And Evolution Of A Unique Housing Pattern In Kerala
Agraharams The Origin And Evolution Of A Unique Housing Pattern In Kerala
 
Geography of india
Geography of indiaGeography of india
Geography of india
 
Finance Quiz
Finance QuizFinance Quiz
Finance Quiz
 

Similar to Minimum Candy Distribution Problem

ADA group final presentation.pptx
ADA group final presentation.pptxADA group final presentation.pptx
ADA group final presentation.pptxSwarajSonavane
 
A simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan ChowdhuryA simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan ChowdhuryS. M. Risalat Hasan Chowdhury
 
Question 1 (5 points)SavedWhich of the following programs woul.pdf
Question 1 (5 points)SavedWhich of the following programs woul.pdfQuestion 1 (5 points)SavedWhich of the following programs woul.pdf
Question 1 (5 points)SavedWhich of the following programs woul.pdfjeetupnl
 
2.7 distributive property day 1
2.7 distributive property day 12.7 distributive property day 1
2.7 distributive property day 1bweldon
 
ML ALL in one (1).pdf
ML ALL in one (1).pdfML ALL in one (1).pdf
ML ALL in one (1).pdfAADITYADARAKH1
 
The lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsThe lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsScott Wlaschin
 
ppt math6 qt3-wk3.pptx
ppt math6 qt3-wk3.pptxppt math6 qt3-wk3.pptx
ppt math6 qt3-wk3.pptxcasafelicemcat04
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programmingOye Tu
 
05 Performing Fundamental Operations on Integers.pptx
05 Performing Fundamental Operations on Integers.pptx05 Performing Fundamental Operations on Integers.pptx
05 Performing Fundamental Operations on Integers.pptxMerrykrisIgnacio
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfShiwani Gupta
 
Class 6 - Maths (Integers).pptx
Class 6 - Maths (Integers).pptxClass 6 - Maths (Integers).pptx
Class 6 - Maths (Integers).pptxSadiqHameed2
 
Coding Concept.ppt
Coding Concept.pptCoding Concept.ppt
Coding Concept.pptssuser3b64952
 
3.1 equation add & subt 1
3.1  equation add & subt 13.1  equation add & subt 1
3.1 equation add & subt 1bweldon
 
epsy applied-cog-psy
epsy applied-cog-psyepsy applied-cog-psy
epsy applied-cog-psyvpletap
 
5As Method of Lesson Plan on Ssolving systems of linear equations in two vari...
5As Method of Lesson Plan on Ssolving systems of linear equations in two vari...5As Method of Lesson Plan on Ssolving systems of linear equations in two vari...
5As Method of Lesson Plan on Ssolving systems of linear equations in two vari...Elton John Embodo
 

Similar to Minimum Candy Distribution Problem (20)

ADA group final presentation.pptx
ADA group final presentation.pptxADA group final presentation.pptx
ADA group final presentation.pptx
 
A simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan ChowdhuryA simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
A simple study on computer algorithms by S. M. Risalat Hasan Chowdhury
 
Question 1 (5 points)SavedWhich of the following programs woul.pdf
Question 1 (5 points)SavedWhich of the following programs woul.pdfQuestion 1 (5 points)SavedWhich of the following programs woul.pdf
Question 1 (5 points)SavedWhich of the following programs woul.pdf
 
2.7 distributive property day 1
2.7 distributive property day 12.7 distributive property day 1
2.7 distributive property day 1
 
ML ALL in one (1).pdf
ML ALL in one (1).pdfML ALL in one (1).pdf
ML ALL in one (1).pdf
 
The lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsThe lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of tests
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 
Unit 2 in daa
Unit 2 in daaUnit 2 in daa
Unit 2 in daa
 
ppt math6 qt3-wk3.pptx
ppt math6 qt3-wk3.pptxppt math6 qt3-wk3.pptx
ppt math6 qt3-wk3.pptx
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
 
05 Performing Fundamental Operations on Integers.pptx
05 Performing Fundamental Operations on Integers.pptx05 Performing Fundamental Operations on Integers.pptx
05 Performing Fundamental Operations on Integers.pptx
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdf
 
Class 6 - Maths (Integers).pptx
Class 6 - Maths (Integers).pptxClass 6 - Maths (Integers).pptx
Class 6 - Maths (Integers).pptx
 
037 lesson 25
037 lesson 25037 lesson 25
037 lesson 25
 
Coding Concept.ppt
Coding Concept.pptCoding Concept.ppt
Coding Concept.ppt
 
Operations on Real Numbers
Operations on Real NumbersOperations on Real Numbers
Operations on Real Numbers
 
3.1 equation add & subt 1
3.1  equation add & subt 13.1  equation add & subt 1
3.1 equation add & subt 1
 
epsy applied-cog-psy
epsy applied-cog-psyepsy applied-cog-psy
epsy applied-cog-psy
 
5As Method of Lesson Plan on Ssolving systems of linear equations in two vari...
5As Method of Lesson Plan on Ssolving systems of linear equations in two vari...5As Method of Lesson Plan on Ssolving systems of linear equations in two vari...
5As Method of Lesson Plan on Ssolving systems of linear equations in two vari...
 
Integer review pp
Integer review ppInteger review pp
Integer review pp
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Dr. Mazin Mohamed alkathiri
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 

Recently uploaded (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

Minimum Candy Distribution Problem

  • 1. The Candy Distribution Problem Dynamic programming 15Z403 - Design and Analysis of Algorithms
  • 2. PROBLEM STATEMENT Alice is a kindergarten teacher. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her performance in the class. Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to minimize the total number of candies she must buy. This above problem is to be solved using Dynamic Programming. 2
  • 3. Design Technique Used Dynamic Programming Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems and stores the results of subproblems to avoid computing the same results again. 3
  • 4. “Dynamic programming is applicable to our problem as it has the following properties : (Optimisation and Overlapping sub-problems) • It can be partitioned into subproblems. • Subproblems can be solved independently, • Solutions (optimal) of the subproblems can be combined to (optimal) solutions of the original problem. • Subproblems have the same property (or are trivial). 4
  • 5. How dynamic programming is used? 1. In Dynamic Programming questions, we are asked to calculate F[i] for some i. Here, F[i] is the number of candies given to child i. (Then we sum the values.) The complexity is that the value F[i] depends on other values, in this case for values of i both smaller and larger. 2. We are calculating candies[i] (number of candies given to child i) in an order such that the “dependencies” (number of candies given to the child-i’s neighbours) for a given value i have already been calculated. (Tabulation). 3. Problem is split into further subproblems whenever duplicates are found in consecutive locations. Example : ratings = [ 2 3 4 5 2 2 7 8 ] It is divided into 2 sub problems as • [ 2 3 4 5 2 ] • [ 2 7 8 ] And their optimal sub-solutions are combined to get optimal solution. (Minimum number of candies). 5
  • 6. N - Number of children. ratings[1:N] - Array that contains ratings of N children. candy_count - Contains the minimum number of candies. is_min(ratings, j) - Checks if the element at position j is a local minimum. is_max(ratings, j) - Checks if the element at position j is a local maximum. find_next_min(ratings, i) - Finds the next local minimum after position i. find_next_max(ratings, i) - Finds the next local maximum after position i. Algorithm Candies : 6
  • 7. Begin 1. Read N. 2. Set prev_repeat = 0, candy_count = 0. 3. Read ratings of n children one by one 2.1 If there are consecutive duplicates, at position i-1, i : 2.2.1 call num_candies(ratings[prev_repeat: i]) 2.2.2 prev_repeat = i 4. candy_count = candy_count + num_candies(ratings[prev_repeat: n]) End Algorithm Candies : 7
  • 8. 1. If number of children = 1, then return 1. 2. Initialize candies[] to zero (all N values). 3. Find first min (next_min) and set candies to 1 4. If the first element is a max, (not a min) 4.1 Iterate from next_min to 0 in reverse 4.1.1 set candies[i] = candies[i+1] + 1 5. Set prev_min = next_min and find new next_min and next_max. Algorithm num_candies(ratings): 8
  • 9. 6. While there is still another min and another max 6.1 candies[next_min] = 1 6.2 Iterate from prev_min to next_max in steps of 1 6.2.1 candies[i] = candies[i - 1] + 1 6.3 Iterate from next_min to next_max in steps of -1 6.3.1 candies[i] = candies[i + 1] + 1 6.4 candies[next_max] = max(candies[next_max - 1], candies[next_max + 1]) + 1 6.5 Same as Step 5 7. If next_max is the last element 7.1 Iterate from prev_min to next_max in steps of -1 7.1.1 candies[i] = candies[i - 1] + 1 7.1.2 candies[next_max] = candies[next_max - 1] + 1 8. return sum of candies[] Algorithm num_candies(ratings) 9
  • 10. Ratings[i] 3 5 Ratings[i] 5 1 9 10 7 8 Candies[i] 0 0 Candies[i] 0 0 0 0 0 0 By Step 3 1 0 By Step 3 0 1 0 0 0 0 By Step 7 1 2 By Step 4 2 1 0 0 0 0 By Step 6.1 2 1 0 0 1 0 By Step 6.2 2 1 2 0 1 0 By Step 6.4 2 1 2 3 1 0 By Step 7 2 1 2 3 1 2 Sum = 3 Sum = 11 Sum = 3+11 = 14 Tracing
  • 11. def is_min(ratings, j): # Checks if the element at position j is a local minimum if j == 0: return ratings[0] < ratings[1] elif j == len(ratings) - 1: return ratings[j - 1] > ratings[j] else: return ratings[j - 1] > ratings[j] and ratings[j] < ratings[j + 1] def is_max(ratings, j): # Checks if the element at position j is a local maximum if j == 0: return ratings[0] > ratings[1] elif j == len(ratings) - 1: return ratings[j - 1] < ratings[j] else: return ratings[j - 1] < ratings[j] and ratings[j] > ratings[j + 1] Source Code - Implementation using Python 3 11
  • 12. def find_next_min(ratings, i): # Finds the next local minimum after position i if i == None: return None for j in range(i + 1, len(ratings)): if is_min(ratings, j): return j return None def find_next_max(ratings, i): # Finds the next local maximum after position i if i == None: return None for j in range(i + 1, len(ratings)): if is_max(ratings, j): return j return None Source Code 12
  • 13. def num_candies(ratings): if len(ratings) == 1: return 1 candies = [0]*len(ratings) # Find first min and set candies to 1 next_min = find_next_min(ratings, -1) candies[next_min] = 1 # If the first element is a max, not a min if next_min != 0: for i in range(next_min - 1, -1, -1): candies[i] = candies[i + 1] + 1 # Find next min and max prev_min = next_min next_max = find_next_max(ratings, prev_min) # next_max after prev_min next_min = find_next_min(ratings, next_max) # next_min after next_max Source Code 13
  • 14. # While there is still another min and another max while next_min and next_max: candies[next_min] = 1 # Iterate inward from mins to max for i in range(prev_min + 1, next_max): candies[i] = candies[i - 1] + 1 for i in range(next_min - 1, next_max, -1): candies[i] = candies[i + 1] + 1 # Set candies of max candies[next_max] = max(candies[next_max - 1], candies[next_max + 1]) + 1 Source Code 14
  • 15. # If next_max is the last element if next_max: for i in range(prev_min + 1, next_max): candies[i] = candies[i - 1] + 1 candies[next_max] = candies[next_max - 1] + 1 return sum(candies) # Main Program N = int(input()) ratings = [int(input())] candy_count = 0 prev_repeat = 0 for i in range(1, N): ratings.append(int(input())) if ratings[i] == ratings[i - 1]: candy_count += num_candies(ratings[prev_repeat: i]) prev_repeat = i candy_count += num_candies(ratings[prev_repeat:]) print(candy_count) Source Code 15
  • 16. Output - Minimum number of Candies 16 Output - (i) Output - (ii)
  • 17. O(n) Time Complexity In the num_candies function, the each of the loops run not more than n times in the worst case, (where n is the number of children) and hence the time taken is linear. 17
  • 18. Thanks! Presentation by Preethi S V (17z231) Sivakami N (17z245) Varsha Devi K (17z256) Samyuktha G (17z238) Tejaswini Sivakumar (17z253) 18