Greedy
Greedy
Greedy
1
Contents
14 Delete an element from array (Using two traversals and one traversal) 87
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
19 Divide cuboid into cubes such that sum of volumes is maximum 141
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
23 Find if k bookings possible with given arrival and departure times 165
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
25 Find maximum height pyramid from the given array of objects 173
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
27 Find minimum number of currency notes and values that sum to given
amount 193
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
28 Find minimum time to finish all jobs with given constraints 199
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
29 Find smallest number with given number of digits and sum of digits 208
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
2
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
31 Find the Largest number with given number of digits and sum of digits 222
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
32 Find the minimum and maximum amount to buy all N candies 231
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
3
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
4
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
74 Minimize Cash Flow among a given set of friends who have borrowed
money from each other 468
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
76 Minimize the sum of product of two arrays with permutations allowed 486
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
77 Minimum Cost Path with Left, Right, Bottom and Up moves allowed 492
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
5
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
82 Minimum cost for acquiring all coins with k extra coins allowed with
every coin 519
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
90 Minimum initial vertices to traverse whole matrix with given conditions 562
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
6
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
101 Minimum sum of two numbers formed from digits of an array 622
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
104 Operating System Program for Next Fit algorithm in Memory Man-
agement 635
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
106 Pair formation such that maximum pair sum is minimized 646
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
108 Partition into two subarrays of lengths k and (N – k) such that the
difference of sums is maximum 654
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
109 Place N^2 numbers in matrix such that every row has an equal sum 659
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
7
Contents
113 Prim’s MST for Adjacency List Representation Greedy Algo-6 677
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
115 Print a closest string that does not contain adjacent duplicates 708
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713
116 Problem Solving for Minimum Spanning Trees (Kruskal’s and Prim’s) 714
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 718
122 Program for Shortest Job First (SJF) scheduling Set 2 (Preemptive) 750
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
123 Program for Shortest Job First (or SJF) scheduling Set 1 (Non- pre-
emptive) 758
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 762
127 Rearrange a string so that all same characters become d distance away 787
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
128 Rearrange characters in a string such that no two adjacent are same 794
8
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
130 Schedule jobs so that each server gets equal load 805
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
131 Scheduling priority tasks in limited time and minimizing loss 810
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813
134 Smallest number with sum of digits as N and divisible by 10^N 822
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 827
135 Smallest subset with sum greater than all other elements 828
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 832
9
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900
Contents
10
Chapter 1
11
Chapter 1. Activity Selection Problem Greedy Algo-1
tion problems. For example, Traveling Salesman Problem is a NP-Hard problem. A Greedy
choice for this problem is to pick the nearest unvisited city from the current city at every
step. This solutions don’t always produce the best optimal solution but can be used to get
an approximately optimal solution.
Let us consider the Activity Selection problem as our first example of Greedy algorithms.
Following is the problem statement.
You are given n activities with their start and finish times. Select the maximum number of
activities that can be performed by a single person, assuming that a person can only work
on a single activity at a time.
Example:
The greedy choice is to always pick the next activity whose finish time is least among the
remaining activities and the start time is more than or equal to the finish time of previously
selected activity. We can sort the activities according to their finishing time so that we
always consider the next activity as minimum finishing time activity.
1) Sort the activities according to their finishing time
2) Select the first activity from the sorted array and print it.
3) Do following for remaining activities in the sorted array.
…….a) If the start time of this activity is greater than or equal to the finish time of previously
selected activity then select this activity and print it.
In the following C implementation, it is assumed that the activities are already sorted
according to their finish time.
C++
12
Chapter 1. Activity Selection Problem Greedy Algo-1
Java
13
Chapter 1. Activity Selection Problem Greedy Algo-1
import java.io.*;
class ActivitySelection
{
// Prints a maximum set of activities that can be done by a single
// person, one at a time.
// n --> Total number of activities
// s[] --> An array that contains start time of all activities
// f[] --> An array that contains finish time of all activities
public static void printMaxActivities(int s[], int f[], int n)
{
int i, j;
printMaxActivities(s, f, n);
}
Python
14
Chapter 1. Activity Selection Problem Greedy Algo-1
def printMaxActivities(s , f ):
n = len(f)
print "The following activities are selected"
Output:
How does Greedy Choice work for Activities sorted according to finish time?
Let the given set of activities be S = {1, 2, 3, ..n} and activities be sorted by finish time.
The greedy choice is to always pick activity 1. How come the activity 1 always provides one
of the optimal solutions. We can prove it by showing that if there is another solution B with
the first activity other than 1, then there is also a solution A of the same size with activity
1 as the first activity. Let the first activity selected by B be k, then there always exist A =
{B – {k}} U {1}.(Note that the activities in B are independent and k has smallest finishing
time among all. Since k is not 1, finish(k) >= finish(1)).
15
Chapter 1. Activity Selection Problem Greedy Algo-1
16
Chapter 1. Activity Selection Problem Greedy Algo-1
// Driver program
int main()
{
Activitiy arr[] = {{5, 9}, {1, 2}, {3, 4}, {0, 6},
{5, 7}, {8, 9}};
int n = sizeof(arr)/sizeof(arr[0]);
printMaxActivities(arr, n);
return 0;
}
Output:
Time Complexity : It takes O(n log n) time if input activities may not be sorted. It takes
O(n) time when it is given that input activities are always sorted.
References:
Introduction to Algorithms by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
Clifford Stein
http://en.wikipedia.org/wiki/Greedy_algorithm
Source
https://www.geeksforgeeks.org/activity-selection-problem-greedy-algo-1/
17
Chapter 2
Applications of Minimum
Spanning Tree Problem
18
Chapter 2. Applications of Minimum Spanning Tree Problem
Indirect applications.
– max bottleneck paths
– LDPC codes for error correction
– image registration with Renyi entropy
– learning salient features for real-time face verification
– reducing data storage in sequencing amino acids in a protein
– model locality of particle interactions in turbulent fluid flows
– autoconfig protocol for Ethernet bridging to avoid cycles in a network
Cluster analysis
k clustering problem can be viewed as finding an MST and deleting the k-1 most
expensive edges.
Sources:
http://www.cs.princeton.edu/courses/archive/spr07/cos226/lectures/mst.pdf
http://www.ics.uci.edu/~eppstein/161/960206.html
Source
https://www.geeksforgeeks.org/applications-of-minimum-spanning-tree/
19
Chapter 3
A naive approach is to run two nested for loops and check for every element which one is
more from i to n being the first loop and the second being from i+1 to n and then from 0
20
Chapter 3. Array element moved by k using single moves
to n-1 and count the number of continuous smaller elements and get the answer.
This will not be efficient enough as it takes O(n*n) .
An efficient approach will be to run a loop from 1 to n and keep track of best (or maximum
element) so far and number of smaller elements than this maximum. If current best loose,
initialize the greater value to the best and the count to 1, as the winner won 1 time already.
If at any step it has won k times, you get your answer. But if k >= n-1, then the maximum
number will be the only answer as it will the most number of times being the greatest. If
while iterating you don’t find any player that has won k times, then the maximum number
which is in the list will always be our answer.
Below is the implementation to the above approach
C++
else
times += 1; // if it wins
21
Chapter 3. Array element moved by k using single moves
// then return
if (times >= k)
return best;
}
Java
class GFG {
22
Chapter 3. Array element moved by k using single moves
// no of wins is 1 now
times = 1;
}
else
// if it wins
times += 1;
System.out.println(winner(a, n, k));
}
}
Python3
23
Chapter 3. Array element moved by k using single moves
if k >= n - 1:
return n
# no of wins is 1 now
times = 1
else:
times += 1 # if it wins
# driver code
a = [ 2, 1, 3, 4, 5 ]
n = len(a)
k = 2
print(winner(a, n, k))
C#
24
Chapter 3. Array element moved by k using single moves
using System;
class GFG {
// no of wins is 1 now
times = 1;
}
else
// if it wins
times += 1;
25
Chapter 3. Array element moved by k using single moves
Console.WriteLine(winner(a, n, k));
}
}
PHP
<?php
// PHP program to find winner of game
// no of wins is 1 now
26
Chapter 3. Array element moved by k using single moves
$times = 1;
}
else
// if it wins
$times += 1;
// Driver Code
$a = array( 2, 1, 3, 4, 5 );
$n = sizeof($a);
$k = 2;
echo(winner($a, $n, $k));
Output :
Source
https://www.geeksforgeeks.org/array-element-moved-k-using-single-moves/
27
Chapter 4
This problem can be solved using greedy strategy. We can put every mouse to its nearest
28
Chapter 4. Assign Mice to Holes
hole to minimize the time. This can be done by sorting the positions of mice and holes.
This allows us to put the ith mice to the corresponding hole in the holes list. We can then
find the maximum difference between the mice and corresponding hole position.
In example 2, on sorting both the lists, we find that the mouse at position -79 is the last to
travel to hole 23 taking time 102.
Loop i = 1 to N:
update ans according to the value
of |mice(i) - hole(i)|. It should
be maximum of all differences.
Proof of correctness:
Let i1 < i2 be the positions of two mice and let j1 < j2 be the positions of two holes. It
suffices to show via case analysis that
Since it follows by induction that every assignment can be transformed by a series of swaps
into the sorted assignment, where none of these swaps increases the span.
29
Chapter 4. Assign Mice to Holes
int max = 0;
for (int i=0; i<size; i++)
if (max < Math.abs(mice.get(i)-holes.get(i)))
max = Math.abs(mice.get(i)-holes.get(i));
return Math.abs(max);
}
Output:
Source
https://www.geeksforgeeks.org/assign-mice-holes/
30
Chapter 5
Lower Bound
We can always find a lower bound on minimum number of bins required. The lower bound
can be given as :
31
Chapter 5. Bin Packing Problem (Minimize number of used Bins)
In the above examples, lower bound for first example is “ceil(4 + 8 + 1 + 4 + 2 + 1)/10”
= 2 and lower bound in second example is “ceil(9 + 8 + 2 + 2 + 5 + 4)/10” = 3.
This problem is a NP Hard problem and finding an exact minimum number of bins takes
exponential time. Following are approximate algorithms for this problem.
Applications
Online Algorithms
These algorithms are for Bin Packing problems where items arrive one at a time (in unknown
order), each must be put in a bin, before considering the next item.
1. Next Fit:
When processing next item, check if it fits in the same bin as the last item. Use a new bin
only if it does not.
Below is C++ implementation for this algorithm.
32
Chapter 5. Bin Packing Problem (Minimize number of used Bins)
{
// If this item can't fit in current bin
if (weight[i] > bin_rem)
{
res++; // Use a new bin
bin_rem = c - weight[i];
}
else
bin_rem -= weight[i];
}
return res;
}
// Driver program
int main()
{
int weight[] = {2, 5, 4, 7, 1, 3, 8};
int c = 10;
int n = sizeof(weight) / sizeof(weight[0]);
cout << "Number of bins required in Next Fit : "
<< nextFit(weight, n, c);
return 0;
}
Output:
Next Fit is a simple algorithm. It requires only O(n) time and O(1) extra space to process
n items.
Next Fit is 2 approximate, i.e., the number of bins used by this algorithm is bounded by
twice of optimal. Consider any two adjacent bins. The sum of items in these two bins must
be > c; otherwise, NextFit would have put all the items of second bin into the first. The
same holds for all other bins. Thus, at most half the space is wasted, and so Next Fit uses
at most 2M bins if M is optimal.
2. First Fit:
When processing the next item, see if it fits in the same bin as the last item. Start a new
bin only if it does not.
33
Chapter 5. Bin Packing Problem (Minimize number of used Bins)
// Driver program
int main()
{
int weight[] = {2, 5, 4, 7, 1, 3, 8};
int c = 10;
int n = sizeof(weight) / sizeof(weight[0]);
cout << "Number of bins required in First Fit : "
<< firstFit(weight, n, c);
return 0;
}
Output:
34
Chapter 5. Bin Packing Problem (Minimize number of used Bins)
The above implementation of First Fit requires O(n2 ) time, but First Fit can be implemented
in O(n Log n) time using Self-Balancing Binary Search Trees.
If M is the optimal number of bins, then First Fit never uses more than 1.7M bins. So First
Fit is better than Next Fit in terms of upper bound on number of bins.
3. Best Fit:
The idea is to places the next item in the *tightest* spot. That is, put it in the bin so that
smallest empty space is left.
35
Chapter 5. Bin Packing Problem (Minimize number of used Bins)
if (min==c+1)
{
bin_rem[res] = c - weight[i];
res++;
}
else // Assign the item to best bin
bin_rem[bi] -= weight[i];
}
return res;
}
// Driver program
int main()
{
int weight[] = {2, 5, 4, 7, 1, 3, 8};
int c = 10;
int n = sizeof(weight) / sizeof(weight[0]);
cout << "Number of bins required in Best Fit : "
<< bestFit(weight, n, c);
return 0;
}
Output:
Best Fit can also be implemented in O(n Log n) time using Self-Balancing Binary Search
Trees.
If M is the optimal number of bins, then Best Fit never uses more than 1.7M bins. So Best
Fit is same as First Fit and better than Next Fit in terms of upper bound on number of
bins.
Offline Algorithms
In the offline version, we have all items upfront. Unfortunately offline version is also NP
Complete, but we have a better approximate algorithm for it. First Fit Decreasing uses at
most (4M + 1)/3 bins if the optimal is M.
4. First Fit Decreasing:
A trouble with online algorithms is that packing large items is difficult, especially if they
occur late in the sequence. We can circumvent this by *sorting* the input sequence, and
placing the large items first. With sorting, we get First Fit Decreasing and Best Fit De-
creasing, as offline analogs of online First Fit and Best Fit.
36
Chapter 5. Bin Packing Problem (Minimize number of used Bins)
// Driver program
int main()
{
int weight[] = {2, 5, 4, 7, 1, 3, 8};
int c = 10;
int n = sizeof(weight) / sizeof(weight[0]);
cout << "Number of bins required in First Fit "
<< "Decreasing : " << firstFitDec(weight, n, c);
return 0;
}
Output:
First Fit decreasing produces the best result for the sample input because items are sorted
first.
First Fit Decreasing can also be implemented in O(n Log n) time using Self-Balancing Binary
Search Trees.
Source:
https://www.cs.ucsb.edu/~suri/cs130b/BinPacking.txt
This article is contributed by Dheeraj Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/bin-packing-problem-minimize-number-of-used-bins/
37
Chapter 6
Source
https://www.geeksforgeeks.org/g-fact-83/
38
Chapter 7
Below is the idea behind above algorithm (The idea is same as Prim’s MST algorithm).
A spanning tree means all vertices must be connected. So the two disjoint subsets (discussed
above) of vertices must be connected to make a Spanning Tree. And they must be connected
with the minimum weight edge to make it a Minimum Spanning Tree.
Let us understand the algorithm with below example.
39
Chapter 7. Boruvka’s algorithm Greedy Algo-9
Initially MST is empty. Every vertex is singe component as highlighted in blue color in
below diagram.
For every component, find the cheapest edge that connects it to some other component.
The cheapest edges are highlighted with green color. Now MST becomes {0-1, 2-8, 2-3, 3-4,
5-6, 6-7}.
40
Chapter 7. Boruvka’s algorithm Greedy Algo-9
After above step, components are {{0,1}, {2,3,4,8}, {5,6,7}}. The components are encircled
with blue color.
We again repeat the step, i.e., for every component, find the cheapest edge that connects it
to some other component.
The cheapest edges are highlighted with green color. Now MST becomes {0-1, 2-8, 2-3, 3-4,
5-6, 6-7, 1-2, 2-5}
At this stage, there is only one component {0, 1, 2, 3, 4, 5, 6, 7, 8} which has all edges.
Since there is only one component left, we stop and return MST.
Implementation:
Below is implementation of above algorithm. The input graph is represented as a collection
of edges and union-find data structure is used to keep track of components.
C/C++
41
Chapter 7. Boruvka’s algorithm Greedy Algo-9
struct Edge
{
int src, dest, weight;
};
42
Chapter 7. Boruvka’s algorithm Greedy Algo-9
subsets[v].parent = v;
subsets[v].rank = 0;
cheapest[v] = -1;
}
if (cheapest[set2] == -1 ||
edge[cheapest[set2]].weight > edge[i].weight)
cheapest[set2] = i;
}
}
43
Chapter 7. Boruvka’s algorithm Greedy Algo-9
if (set1 == set2)
continue;
MSTweight += edge[cheapest[i]].weight;
printf("Edge %d-%d included in MST\n",
edge[cheapest[i]].src, edge[cheapest[i]].dest);
44
Chapter 7. Boruvka’s algorithm Greedy Algo-9
return subsets[i].parent;
}
45
Chapter 7. Boruvka’s algorithm Greedy Algo-9
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 6;
boruvkaMST(graph);
return 0;
}
Python
def __init__(self,vertices):
self.V= vertices #No. of vertices
self.graph = [] # default dictionary to store graph
46
Chapter 7. Boruvka’s algorithm Greedy Algo-9
if parent[i] == i:
return i
return self.find(parent, parent[i])
47
Chapter 7. Boruvka’s algorithm Greedy Algo-9
for i in range(len(self.graph)):
if set1 != set2 :
MSTweight += w
self.union(parent, rank, set1, set2)
print ("Edge %d-%d with weight %d included in MST" % (u,v,w))
numTrees = numTrees - 1
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
48
Chapter 7. Boruvka’s algorithm Greedy Algo-9
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
g.boruvkaMST()
Output:
Source
https://www.geeksforgeeks.org/boruvkas-algorithm-greedy-algo-9/
49
Chapter 8
The idea is to use greedy approach, where we should start buying product from the day
when the stock price is least and so on.
So, we will sort the pair of two values i.e { stock price, day } according to the stock price,
and if stock prices are same, then we sort according to the day.
Now, we will traverse along the sorted list of pairs, and start buying as follows:
50
Chapter 8. Buy Maximum Stocks if i stocks can be bought on i-th day
Let say, we have R rs remaining till now, and the cost of product on this day be C, and we
can buy atmost L products on this day then,
total purchase on this day (P) = min(L, R/C)
Now, add this value to the answer.
total purchase on this day (P) = min(L, R/C)
Now, add this value to the answer
total_purchase = total_purchase + P, where P =min(L, R/C)
Now, substract the cost of buying P items from remaining money, R = R – P*C.
Total number of products that we can buy is equal to total_purchase.
Below is C++ implementation of this approach:
return ans;
}
// Driven Program
int main()
{
int price[] = { 10, 7, 19 };
int n = sizeof(price)/sizeof(price[0]);
int k = 45;
51
Chapter 8. Buy Maximum Stocks if i stocks can be bought on i-th day
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/buy-maximum-stocks-stocks-can-bought-th-day/
52
Chapter 9
Currently, it’s Monday, and you need to survive for the next S days.
Find the minimum number of days on which you need to buy food from the
shop so that you can survive the next S days, or determine that it isn’t possible to
survive.
Examples:
Input : S = 10 N = 16 M = 2
Output : Yes 2
Explanation 1: One possible solution is to buy a box on the first day (Monday),
it’s sufficient to eat from this box up to 8th day (Monday) inclusive. Now, on the
9th day (Tuesday), you buy another box and use the chocolates in it to survive
the 9th and 10th day.
Input : 10 20 30
Output : No
Explanation 2: You can’t survive even if you buy food because the maximum
number of units you can buy in one day is less the required food for one day.
53
Chapter 9. Check if it is possible to survive on Island
Approach:
In this problem, the greedy approach of buying the food for some consecutive early days is
the right direction.
If we can survive for the first 7 days then we can survive any number of days for that we
need to check two things
-> Check whether we can survive one day or not.
-> (S >= 7) If we buy food in the first 6 days of the week and we can survive for the week
i.e. total food we can buy in a week (6*N) is greater then or equal to total food we require
to survive in a week (7*M) then we can survive.
If any of the above conditions are not true then we can’t survive else the minimum number
of days required to buy food will be = ceil(total food required/units of food we can buy
each day)
CPP
// Driver code
int main()
{
int S = 10, N = 16, M = 2;
survival(S, N, M);
return 0;
}
54
Chapter 9. Check if it is possible to survive on Island
Java
class GFG {
else {
if (((M * S) % N) != 0)
days++;
// Driver code
public static void main(String[] args)
{
int S = 10, N = 16, M = 2;
survival(S, N, M);
}
}
Python3
55
Chapter 9. Check if it is possible to survive on Island
if (((M * S) % N) != 0):
days += 1
print("Yes "),
print(days)
# Driver code
S = 10; N = 16; M = 2
survival(S, N, M)
C#
class GFG {
56
Chapter 9. Check if it is possible to survive on Island
if (((M * S) % N) != 0)
days++;
// Driver code
public static void Main()
{
int S = 10, N = 16, M = 2;
survival(S, N, M);
}
}
PHP
<?php
// PHP program to find the
// minimum days on which
// you need to buy food
// from the shop so that you
// can survive the next S days
// Function to find
// the minimum $days
function survival($S, $N, $M)
{
57
Chapter 9. Check if it is possible to survive on Island
echo "No";
else
{
// Driver code
$S = 10; $N = 16; $M = 2;
survival($S, $N, $M);
?>
Output:
Yes 2
Source
https://www.geeksforgeeks.org/survival/
58
Chapter 10
59
Chapter 10. Coin Change DP-7
Java
class GFG {
60
Chapter 10. Coin Change DP-7
Python3
# If n is 0 then there is 1
# solution (do not include any coin)
if (n == 0):
return 1
61
Chapter 10. Coin Change DP-7
if (n < 0):
return 0;
C#
class GFG
{
// Returns the count of ways we can
// sum S[0...m-1] coins to get sum n
static int count( int []S, int m, int n )
{
// If n is 0 then there is 1 solution
// (do not include any coin)
if (n == 0)
return 1;
62
Chapter 10. Coin Change DP-7
// Driver program
public static void Main()
{
}
}
// This code is contributed by Sam007
PHP
<?php
// Recursive PHP program for
// coin change problem.
// If n is 0 then there is
// 1 solution (do not include
// any coin)
if ($n == 0)
return 1;
63
Chapter 10. Coin Change DP-7
// Driver Code
$arr = array(1, 2, 3);
$m = count($arr);
echo coun($arr, $m, 4);
Output :
It should be noted that the above function computes the same subproblems again and again.
See the following recursion tree for S = {1, 2, 3} and n = 5.
The function C({1}, 3) is called two times. If we draw the complete tree, then we can see
that there are many subproblems being called more than once.
Since same suproblems are called again, this problem has Overlapping Subprolems property.
So the Coin Change problem has both properties (see thisand this) of a dynamic program-
ming problem. Like other typical Dynamic Programming(DP) problems, recomputations of
same subproblems can be avoided by constructing a temporary array table[][] in bottom up
manner.
64
Chapter 10. Coin Change DP-7
// total count
table[i][j] = x + y;
}
}
return table[n][m-1];
}
65
Chapter 10. Coin Change DP-7
Java
class CoinChange
{
static long countWays(int S[], int m, int n)
{
//Time complexity of this function: O(mn)
//Space Complexity of this function: O(n)
return table[n];
}
Python
66
Chapter 10. Coin Change DP-7
# total count
table[i][j] = x + y
return table[n][m-1]
C#
class GFG
{
static long countWays(int []S, int m, int n)
{
//Time complexity of this function: O(mn)
//Space Complexity of this function: O(n)
67
Chapter 10. Coin Change DP-7
return table[n];
}
// Driver Function
public static void Main()
{
int []arr = {1, 2, 3};
int m = arr.Length;
int n = 4;
Console.Write(countWays(arr, m, n));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program for
// coin change problem.
68
Chapter 10. Coin Change DP-7
// value case (n = 0)
$table;
for ($i = 0; $i < $n + 1; $i++)
for ($j = 0; $j < $m; $j++)
$table[$i][$j] = 0;
// Count of solutions
// excluding S[j]
$y = ($j >= 1) ?
$table[$i][$j - 1] : 0;
// total count
$table[$i][$j] = $x + $y;
}
}
return $table[$n][$m-1];
}
// Driver Code
$arr = array(1, 2, 3);
$m = count($arr);
$n = 4;
echo count1($arr, $m, $n);
Output:
69
Chapter 10. Coin Change DP-7
Following is a simplified version of method 2. The auxiliary space required here is O(n)
only.
C
// Pick all coins one by one and update the table[] values
// after the index greater than or equal to the value of the
// picked coin
for(int i=0; i<m; i++)
for(int j=S[i]; j<=n; j++)
table[j] += table[j-S[i]];
return table[n];
}
Java
// Pick all coins one by one and update the table[] values
// after the index greater than or equal to the value of the
// picked coin
for(int i=0; i<m; i++)
for(int j=S[i]; j<=n; j++)
table[j] += table[j-S[i]];
return table[n];
}
70
Chapter 10. Coin Change DP-7
Python
# Pick all coins one by one and update the table[] values
# after the index greater than or equal to the value of the
# picked coin
for i in range(0,m):
for j in range(S[i],n+1):
table[j] += table[j-S[i]]
return table[n]
Source
https://www.geeksforgeeks.org/coin-change-dp-7/
71
Chapter 11
Note that the strategy to pick maximum of two corners may not work. In the following
72
Chapter 11. Coin game of two corners (Greedy Approach)
example, first player looses the game when he/she uses strategy to pick maximum of two
corners.
Example:
18 20 15 30 10 14
First Player picks 18, now row of coins is
20 15 30 10 14
Second player picks 20, now row of coins is
15 30 10 14
First Player picks 15, now row of coins is
30 10 14
Second player picks 30, now row of coins is
10 14
First Player picks 14, now row of coins is
10
Second player picks 10, game over.
Note that this problem is different from Optimal Strategy for a Game DP-31. There the
target is to get maximum value. Here the target is to not loose. We have a Greedy Strategy
here. The idea is to count sum of values of all even coins and odd coins, compare the two
values. The player that makes the first move can always make sure that the other player is
never able to choose an even coin if sum of even coins is higher. Similarly, he/she can make
sure that the other player is never able to choose an odd coin if sum of odd coins is higher.
Example:
18 20 15 30 10 14
Sum of odd coins = 18 + 15 + 10 = 43
Sum of even coins = 20 + 30 + 14 = 64.
Since the sum of even coins is more, the first
player decides to collect all even coins. He first
picks 14, now the other player can only pick a coin
(10 or 18). Whichever is picked the other player,
the first player again gets an opportunity to pick
an even coin and block all even coins.
C++
73
Chapter 11. Coin game of two corners (Greedy Approach)
int arr2[] = { 2, 2, 2, 2 };
n = sizeof(arr2) / sizeof(arr2[0]);
printCoins(arr2, n);
cout << endl;
return 0;
}
Java
// Java program to find coins to be
// picked to make sure that we never loose.
class GFG
{
74
Chapter 11. Coin game of two corners (Greedy Approach)
oddSum = 0
evenSum = 0
75
Chapter 11. Coin game of two corners (Greedy Approach)
for i in range(start, n) :
print(arr[i], end = " ")
# Driver code
if __name__ == "__main__" :
arr2 = [2, 2, 2, 2]
n = len(arr2)
printCoins(arr2, n)
print()
C#
// C# program to find coins to be
// picked to make sure that we never loose.
using System;
class GFG
{
// Returns optimal value possible
// that a player can collect from
// an array of coins of size n.
// Note than n must be even
static void printCoins(int[] arr, int n)
{
// Find sum of odd positioned coins
int oddSum = 0;
for (int i = 0; i < n; i += 2) oddSum += arr[i]; // Find sum of even positioned coins int
evenSum = 0; for (int i = 0; i < n; i += 2) evenSum += arr[i]; // Print even or odd coins
depending // upon which sum is greater. int start = ((oddSum > evenSum) ? 0 : 1);
for (int i = start; i < n; i++) Console.Write(arr[i]+” ”); } // Driver Code public static
void Main() { int[] arr1 = { 8, 15, 3, 7 }; int n = arr1.Length; printCoins(arr1, n); Con-
sole.Write(”\n”); int[] arr2 = { 2, 2, 2, 2 }; n = arr2.Length; printCoins(arr2, n); Con-
sole.Write(”\n”); int[] arr3 = { 20, 30, 2, 2, 2, 10 }; n = arr3.Length; printCoins(arr3, n); }
} // This code is contributed by ChitraNayal [tabby title=”PHP”] $evenSum) ? 0 : 1);
for ($i = $start; $i < $n; $i++) echo $arr[$i].” ”; } // Driver Code $arr1 = array( 8, 15, 3,
7 ); $n = sizeof($arr1); printCoins($arr1, $n); echo ”\n”; $arr2 = array( 2, 2, 2, 2 ); $n =
76
Chapter 11. Coin game of two corners (Greedy Approach)
15 3 7
2 2 2
30 2 2 2 10
Source
https://www.geeksforgeeks.org/coin-game-of-two-corners-greedy-approach/
77
Chapter 12
If we observe the above problem closely, we can notice that the lengths of the ropes which
are picked first are included more than once in total cost. Therefore, the idea is to connect
smallest two ropes first and recur for remaining ropes. This approach is similar to Huffman
Coding. We put smallest ropes down the tree so that they can be repeated multiple times
rather than the longer ropes.
Following is complete algorithm for finding the minimum cost for connecting n ropes.
Let there be n ropes of lengths stored in an array len[0..n-1]
1) Create a min heap and insert all lengths into the min heap.
2) Do following while number of elements in min heap is not one.
……a) Extract the minimum and second minimum from min heap
……b) Add the above two extracted values and insert the added value to the min-heap.
……c) Maintain a variable for total cost and keep incrementing it by the sum of extracted
78
Chapter 12. Connect n ropes with minimum cost
values.
3) Return the value of this total cost.
Following is C++ implementation of above algorithm.
79
Chapter 12. Connect n ropes with minimum cost
smallest = right;
if (smallest != idx)
{
swapMinHeapNode(&minHeap->harr[smallest], &minHeap->harr[idx]);
minHeapify(minHeap, smallest);
}
}
// Creates a min heap of capacity equal to size and inserts all values
80
Chapter 12. Connect n ropes with minimum cost
// The main function that returns the minimum cost to connect n ropes of
// lengths stored in len[0..n-1]
int minCost(int len[], int n)
{
int cost = 0; // Initialize result
Output:
81
Chapter 12. Connect n ropes with minimum cost
Time Complexity: Time complexity of the algorithm is O(nLogn) assuming that we use a
O(nLogn) sorting algorithm. Note that heap operations like insert and extract take O(Logn)
time.
Algorithmic Paradigm: Greedy Algorithm
A simple implementation with STL in C++
Following is a simple implementation that uses priority_queue available in STL. Thanks to
Pango89 for providing below code.
C++
#include<iostream>
#include<queue>
// Initialize result
int res = 0;
return res;
}
82
Chapter 12. Connect n ropes with minimum cost
Java
class ConnectRopes
{
static int minCost(int arr[], int n)
{
// Create a priority queue
PriorityQueue<Integer> pq =
new PriorityQueue<Integer>();
// Initialize result
int res = 0;
return res;
}
83
Chapter 12. Connect n ropes with minimum cost
{
int len[] = {4, 3, 2, 6};
int size = len.length;
System.out.println("Total cost for connecting"+
" ropes is " + minCost(len, size));
}
}
// This code is contributed by yash_pec
Output:
This article is compiled by Abhishek. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : JAGRITIBANSAL, AbhijeetSrivastava
Source
https://www.geeksforgeeks.org/connect-n-ropes-minimum-cost/
84
Chapter 13
Correctness of Greedy
Algorithms
85
Chapter 13. Correctness of Greedy Algorithms
Source
https://www.geeksforgeeks.org/correctness-greedy-algorithms/
86
Chapter 14
Delete an element from array (Using two traversals and one traversal) - GeeksforGeeks
Given an array and a number ‘x’, write a function to delete ‘x’ from the given array.
A simple solution is to first search ‘x’ in array, then elements that are on right side of x to
one position back. The following are the implementation of this simple approach.
C/C++
87
Chapter 14. Delete an element from array (Using two traversals and one traversal)
// If x found in array
if (i < n)
{
// reduce size of array and move all
// elements on space ahead
n = n - 1;
for (int j=i; j<n; j++)
arr[j] = arr[j+1];
}
return n;
}
return 0;
}
Java
class Deletion {
88
Chapter 14. Delete an element from array (Using two traversals and one traversal)
// If x found in array
if (i < n)
{
// reduce size of array and move all
// elements on space ahead
n = n - 1;
for (int j=i; j<n; j++)
arr[j] = arr[j+1];
}
return n;
}
}
}
/*This code is contributed by Devesh Agrawal*/
C#
class GFG {
89
Chapter 14. Delete an element from array (Using two traversals and one traversal)
// Search x in array
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
break;
// If x found in array
if (i < n)
{
return n;
}
}
}
Output:
Modified array is
11 15 8 9 10
The above method requires two traversals of array, one for searching and other for moving
elements.
90
Chapter 14. Delete an element from array (Using two traversals and one traversal)
return (n-1);
}
91
Chapter 14. Delete an element from array (Using two traversals and one traversal)
return 0;
}
Java
class Deletion
{
// This function removes an element x from arr[] and
// returns new size after removal.
// Returned size is n-1 when element is present.
// Otherwise 0 is returned to indicate failure.
static int deleteElement(int arr[], int n, int x)
{
// If x is last element, nothing to do
if (arr[n-1] == x)
return (n-1);
return (n-1);
}
92
Chapter 14. Delete an element from array (Using two traversals and one traversal)
}
}
/*This code is contributed by Devesh Agrawal*/
C#
// If x is last element,
// nothing to do
if (arr[n - 1] == x)
return (n - 1);
93
Chapter 14. Delete an element from array (Using two traversals and one traversal)
// If element was
// not found
if (i < 0)
return 0;
return (n - 1);
}
// Driver Code
public static void Main()
{
int []arr = {11, 15, 6, 8, 9, 10};
int n = arr.Length;
int x = 6;
}
}
Output:
Modified array is
11 15 8 9 10
Deleting an element from an array takes O(n) time even if we are given index of the element
to be deleted. The time complexity remains O(n) for sorted arrays as well.
In linked list, if we know the pointer to the previous node of the node to be deleted, we can
do deletion in O(1) time.
This article is contributed by Himanshu. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : nitin mittal, vt_m
94
Chapter 14. Delete an element from array (Using two traversals and one traversal)
Source
https://www.geeksforgeeks.org/delete-an-element-from-array-using-two-traversals-and-one-traversal/
95
Chapter 15
Can we optimize Dijkstra’s shortest path algorithm to work better than O(E
log V) if maximum weight is small (or range of edge weights is small)?
For example, in the above diagram, maximum weight is 14. Many a times the range of
weights on edges in is in small range (i.e. all edge weight can be mapped to 0, 1, 2.. w
where w is a small number). In that case, Dijkstra’s algorithm can be modified by using
different data structure, buckets, which is called dial implementation of dijkstra’s algorithm.
96
Chapter 15. Dial’s Algorithm (Optimized Dijkstra for small range weights)
time complexity is O(E + WV) where W is maximum weight on any edge of graph, so
we can see that, if W is small then this implementation runs much faster than traditional
algorithm. Following are important observations.
• Maximum distance between any two node can be at max w(V – 1) (w is maximum
edge weight and we can have at max V-1 edges between two vertices).
• In Dijkstra algorithm, distances are finalized in non-decreasing, i.e., distance of the
closer (to given source) vertices is finalized before the distant vertices.
Algorithm
Below is complete algorithm:
4. Buckets 0, 1, 2,..wV are checked sequentially until the first non-empty bucket is found.
Each node contained in the first non-empty bucket has the minimum distance label
by definition.
5. One by one, these nodes with minimum distance label are permanently labeled and
deleted from the bucket during the scanning process.
Implementation
Since the maximum distance can be w(V – 1), we create wV buckets (more for simplicity of
code) for implementation of algorithm which can be large if w is big.
97
Chapter 15. Dial’s Algorithm (Optimized Dijkstra for small range weights)
public:
Graph(int V); // Constructor
98
Chapter 15. Dial’s Algorithm (Optimized Dijkstra for small range weights)
B[0].push_back(src);
dist[src].first = 0;
//
int idx = 0;
while (1)
{
// Go sequentially through buckets till one non-empty
// bucket is found
while (B[idx].size() == 0 && idx < W*V)
idx++;
int du = dist[u].first;
int dv = dist[v].first;
99
Chapter 15. Dial’s Algorithm (Optimized Dijkstra for small range weights)
return 0;
}
100
Chapter 15. Dial’s Algorithm (Optimized Dijkstra for small range weights)
Output:
Illustration
Below is step by step illustration taken from here.
101
Chapter 15. Dial’s Algorithm (Optimized Dijkstra for small range weights)
102
Chapter 15. Dial’s Algorithm (Optimized Dijkstra for small range weights)
103
Chapter 15. Dial’s Algorithm (Optimized Dijkstra for small range weights)
104
Chapter 15. Dial’s Algorithm (Optimized Dijkstra for small range weights)
105
Chapter 15. Dial’s Algorithm (Optimized Dijkstra for small range weights)
106
Chapter 15. Dial’s Algorithm (Optimized Dijkstra for small range weights)
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/dials-algorithm-optimized-dijkstra-for-small-range-weights/
107
Chapter 16
108
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
distance value is more than weight of u-v plus distance value of u, then update the distance
value of v.
Let us understand with the following example. Let the given source vertex be 0
Initially, distance value of source vertex is 0 and INF (infinite) for all other vertices. So
source vertex is extracted from Min Heap and distance values of vertices adjacent to 0 (1
and 7) are updated. Min Heap contains all vertices except vertex 0.
The vertices in green color are the vertices for which minimum distances are finalized and
are not in Min Heap
Since distance value of vertex 1 is minimum among all nodes in Min Heap, it is extracted from
Min Heap and distance values of vertices adjacent to 1 are updated (distance is updated if
the a vertex is not in Min Heap and distance through 1 is shorter than the previous distance).
Min Heap contains all vertices except vertex 0 and 1.
Pick the vertex with minimum distance value from min heap. Vertex 7 is picked. So min
heap now contains all vertices except 0, 1 and 7. Update the distance values of adjacent
vertices of 7. The distance value of vertex 6 and 8 becomes finite (15 and 9 respectively).
109
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
Pick the vertex with minimum distance from min heap. Vertex 6 is picked. So min heap now
contains all vertices except 0, 1, 7 and 6. Update the distance values of adjacent vertices of
6. The distance value of vertex 5 and 8 are updated.
Above steps are repeated till min heap doesn’t become empty. Finally, we get the following
shortest path tree.
C++
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
110
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
};
return graph;
}
111
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
112
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
// A utility function to swap two nodes of min heap. Needed for min heapify
void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b)
{
struct MinHeapNode* t = *a;
*a = *b;
*b = t;
}
if (smallest != idx)
{
// The nodes to be swapped in min heap
MinHeapNode *smallestNode = minHeap->array[smallest];
MinHeapNode *idxNode = minHeap->array[idx];
// Swap positions
minHeap->pos[smallestNode->v] = idx;
minHeap->pos[idxNode->v] = smallest;
// Swap nodes
swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
113
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
return root;
}
114
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
// The main function that calulates distances of shortest paths from src to all
// vertices. It is a O(ELogV) function
void dijkstra(struct Graph* graph, int src)
{
int V = graph->V;// Get the number of vertices in graph
int dist[V]; // dist values used to pick minimum weight edge in cut
// Initialize min heap with all vertices. dist value of all vertices
for (int v = 0; v < V; ++v)
{
dist[v] = INT_MAX;
minHeap->array[v] = newMinHeapNode(v, dist[v]);
minHeap->pos[v] = v;
}
115
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
while (!isEmpty(minHeap))
{
// Extract the vertex with minimum distance value
struct MinHeapNode* minHeapNode = extractMin(minHeap);
int u = minHeapNode->v; // Store the extracted vertex number
116
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
addEdge(graph, 5, 6, 2);
addEdge(graph, 6, 7, 1);
addEdge(graph, 6, 8, 6);
addEdge(graph, 7, 8, 7);
dijkstra(graph, 0);
return 0;
}
Python
class Heap():
def __init__(self):
self.array = []
self.size = 0
self.pos = []
117
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
smallest = left
# Swap positions
self.pos[ self.array[smallest][0] ] = idx
self.pos[ self.array[idx][0] ] = smallest
# Swap nodes
self.swapMinHeapNode(smallest, idx)
self.minHeapify(smallest)
return root
def isEmpty(self):
return True if self.size == 0 else False
118
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
i = self.pos[v]
class Graph():
119
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
120
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
v = pCrawl[0]
printArr(dist,V)
Output:
121
Chapter 16. Dijkstra’s Algorithm for Adjacency List Representation Greedy Algo-8
7 8
8 14
Time Complexity: The time complexity of the above code/algorithm looks O(V^2) as
there are two nested while loops. If we take a closer look, we can observe that the statements
in inner loop are executed O(V+E) times (similar to BFS). The inner loop has decreaseKey()
operation which takes O(LogV) time. So overall time complexity is O(E+V)*O(LogV) which
is O((E+V)*LogV) = O(ELogV)
Note that the above code uses Binary Heap for Priority Queue implementation. Time com-
plexity can be reduced to O(E + VLogV) using Fibonacci Heap. The reason is, Fibonacci
Heap takes O(1) time for decrease-key operation while Binary Heap takes O(Logn) time.
Notes:
1) The code calculates shortest distance, but doesn’t calculate the path information. We
can create a parent array, update the parent array when distance is updated (like prim’s
implementation) and use it show the shortest path from source to different vertices.
2) The code is for undirected graph, same dijekstra function can be used for directed graphs
also.
3) The code finds shortest distances from source to all vertices. If we are interested only in
shortest distance from source to a single target, we can break the for loop when the picked
minimum distance vertex is equal to target (Step 3.a of algorithm).
4) Dijkstra’s algorithm doesn’t work for graphs with negative weight edges. For graphs with
negative weight edges, Bellman–Ford algorithm can be used, we will soon be discussing it
as a separate post.
Printing Paths in Dijkstra’s Shortest Path Algorithm
Dijkstra’s shortest path algorithm using set in STL
References:
Introduction to Algorithms by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson,
Ronald L.
Algorithms by Sanjoy Dasgupta, Christos Papadimitriou, Umesh Vazirani
Source
https://www.geeksforgeeks.org/dijkstras-algorithm-for-adjacency-list-representation-greedy-algo-8/
122
Chapter 17
Dijsktra’s algorithm
Given a graph and a source vertex in the graph, find shortest paths from source to all
vertices in the given graph.
Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like
Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We maintain
two sets, one set contains vertices included in shortest path tree, other set includes vertices
not yet included in shortest path tree. At every step of the algorithm, we find a vertex
which is in the other set (set of not yet included) and has a minimum distance from the
source.
Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a
single source vertex to all other vertices in the given graph.
Algorithm
1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest
path tree, i.e., whose minimum distance from source is calculated and finalized. Initially,
this set is empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values as
INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
3) While sptSet doesn’t include all vertices
….a) Pick a vertex u which is not there in sptSet and has minimum distance value.
….b) Include u to sptSet.
….c) Update distance value of all adjacent vertices of u. To update the distance values,
iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value
of u (from source) and weight of edge u-v, is less than the distance value of v, then update
the distance value of v.
Let us understand with the following example:
123
Chapter 17. Dijkstra’s shortest path algorithm Greedy Algo-7
The set sptSet is initially empty and distances assigned to vertices are {0, INF, INF, INF,
INF, INF, INF, INF} where INF indicates infinite. Now pick the vertex with minimum
distance value. The vertex 0 is picked, include it in sptSet. So sptSet becomes {0}. After
including 0 to sptSet, update distance values of its adjacent vertices. Adjacent vertices of
0 are 1 and 7. The distance values of 1 and 7 are updated as 4 and 8. Following subgraph
shows vertices and their distance values, only the vertices with finite distance values are
shown. The vertices included in SPT are shown in green colour.
Pick the vertex with minimum distance value and not already included in SPT (not in
sptSET). The vertex 1 is picked and added to sptSet. So sptSet now becomes {0, 1}.
Update the distance values of adjacent vertices of 1. The distance value of vertex 2 becomes
12.
Pick the vertex with minimum distance value and not already included in SPT (not in
sptSET). Vertex 7 is picked. So sptSet now becomes {0, 1, 7}. Update the distance values
of adjacent vertices of 7. The distance value of vertex 6 and 8 becomes finite (15 and 9
respectively).
124
Chapter 17. Dijkstra’s shortest path algorithm Greedy Algo-7
Pick the vertex with minimum distance value and not already included in SPT (not in
sptSET). Vertex 6 is picked. So sptSet now becomes {0, 1, 7, 6}. Update the distance
values of adjacent vertices of 6. The distance value of vertex 5 and 8 are updated.
We repeat the above steps until sptSet doesn’t include all vertices of given graph. Finally,
we get the following Shortest Path Tree (SPT).
#include <stdio.h>
#include <limits.h>
125
Chapter 17. Dijkstra’s shortest path algorithm Greedy Algo-7
#define V 9
// A utility function to find the vertex with minimum distance value, from
// the set of vertices not yet included in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;
return min_index;
}
126
Chapter 17. Dijkstra’s shortest path algorithm Greedy Algo-7
dijkstra(graph, 0);
return 0;
}
Java
class ShortestPath
{
127
Chapter 17. Dijkstra’s shortest path algorithm Greedy Algo-7
return min_index;
}
128
Chapter 17. Dijkstra’s shortest path algorithm Greedy Algo-7
// Driver method
public static void main (String[] args)
{
/* Let us create the example graph discussed above */
int graph[][] = new int[][]{{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
ShortestPath t = new ShortestPath();
t.dijkstra(graph, 0);
}
}
//This code is contributed by Aakash Hasija
129
Chapter 17. Dijkstra’s shortest path algorithm Greedy Algo-7
Python
class Graph():
return min_index
130
Chapter 17. Dijkstra’s shortest path algorithm Greedy Algo-7
self.printSolution(dist)
# Driver program
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
];
g.dijkstra(0);
Output:
131
Chapter 17. Dijkstra’s shortest path algorithm Greedy Algo-7
7 8
8 14
Notes:
1) The code calculates shortest distance, but doesn’t calculate the path information. We
can create a parent array, update the parent array when distance is updated (like prim’s
implementation) and use it show the shortest path from source to different vertices.
2) The code is for undirected graph, same dijkstra function can be used for directed graphs
also.
3) The code finds shortest distances from source to all vertices. If we are interested only in
shortest distance from the source to a single target, we can break the for the loop when the
picked minimum distance vertex is equal to target (Step 3.a of the algorithm).
4) Time Complexity of the implementation is O(V^2). If the input graph is represented
using adjacency list, it can be reduced to O(E log V) with the help of binary heap. Please
see
Dijkstra’s Algorithm for Adjacency List Representation for more details.
5) Dijkstra’s algorithm doesn’t work for graphs with negative weight edges. For graphs with
negative weight edges, Bellman–Ford algorithm can be used, we will soon be discussing it
as a separate post.
Dijkstra’s Algorithm for Adjacency List Representation
Printing Paths in Dijkstra’s Shortest Path Algorithm
Dijkstra’s shortest path algorithm using set in STL
Source
https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/
132
Chapter 18
Input : 5
Output : 2
5 2
3
4 3 1
Here sum of group 1 is 7 and sum of group 2 is 8.
Their absolute difference is 1 which is minimum.
We can have multiple correct answers. (1, 2, 5) and
(3, 4) is another such group.
Input : 6
Output : 2
6 4
4
5 3 2 1
We can always divide sum of n integers in two groups such that their absolute difference of
their sum is 0 or 1. So sum of group at most differ by 1. We define sum of group1 as half
of n elements sum.
Now run a loop from n to 1 and insert i into group1 if inserting an element doesn’t exceed
133
Chapter 18. Divide 1 to n into two groups with minimum sum difference
group1.push_back(i);
134
Chapter 18. Divide 1 to n into two groups with minimum sum difference
group2.push_back(i);
}
}
Java
class GFG
{
// To print vector along size
static void printVector(Vector<Integer> v)
{
// Print vector size
System.out.println(v.size());
System.out.println();
}
135
Chapter 18. Divide 1 to n into two groups with minimum sum difference
group1.add(i);
// Driver code
public static void main (String[] args)
{
int n = 5;
findTwoGroup(n);
}
}
Python3
136
Chapter 18. Divide 1 to n into two groups with minimum sum difference
print()
group1=[]
group2=[]
for i in range(n, 0, -1):
else :
group2.append(i)
# driver code
n = 5
findTwoGroup(n)
C#
137
Chapter 18. Divide 1 to n into two groups with minimum sum difference
138
Chapter 18. Divide 1 to n into two groups with minimum sum difference
<?php
// PHP program to divide n
// integers in two groups
// such that absolute
// difference of their
// sum is minimum
// To print vector
// along size
function printVector($v)
{
// Print vector size
echo count($v) . "\n";
echo "\n";
}
// Sum of elements
// of group1
$group1Sum = (int)($sum / 2);
$group1;
$group2;
$x = 0;
$y = 0;
139
Chapter 18. Divide 1 to n into two groups with minimum sum difference
// i in group 1 otherwise
// include in group2
if ($group1Sum - $i >= 0)
{
$group1[$x++] = $i;
// Decrease sum
// of group1
$group1Sum -= $i;
}
else
{
$group2[$y++] = $i;
}
}
// Driver Code
$n = 5;
findTwoGroup($n);
Output:
2
5 2
3
4 3 1
Source
https://www.geeksforgeeks.org/divide-1-n-two-groups-minimum-sum-difference/
140
Chapter 19
Divide cuboid into cubes such that sum of volumes is maximum - GeeksforGeeks
Given the length, breadth, height of a cuboid. The task is to divide the given cuboid in
minimum number of cubes such that size of all cubes is same and sum of volumes of cubes
is maximum.
Examples:
Input : l = 2, b = 4, h = 6
Output : 2 6
A cuboid of length 2, breadth 4 and
height 6 can be divided into 6 cube
of side equal to 2.
Volume of cubes = 6*(2*2*2) = 6*8 = 48.
Volume of cuboid = 2*4*6 = 48.
Input : 1 2 3
Output : 1 6
First of all, we are not allowed to waste volume of cuboid as we meed maximum volume
sum. So, each side should be completely divide among all cubes. And since each of three
side of cubes are equal, so each side of the cuboid need to be divisible by same number,
say x, which will going to be the side of the cube. So, we have to maximize this x, which
will divide given length, breadth and height. This x will be maximum only if it is greatest
common divisor of given length, breadth and height. So, the length of the cube will be GCD
of length, breadth and height.
141
Chapter 19. Divide cuboid into cubes such that sum of volumes is maximum
Now, to compute number of cubes, we know total volume of cuboid and can find volume of
one cube (since side is already calculated). So, total number of cubes is equal to (volume of
cuboid)/(volume of cube) i.e (l * b * h)/(x * x * x).
Below is implementation of this approach:
C++
cout << side << " " << num << endl;
}
// Driver code
int main()
{
int l = 2, b = 4, h = 6;
maximizecube(l, b, h);
return 0;
}
Java
class GFG {
142
Chapter 19. Divide cuboid into cubes such that sum of volumes is maximum
return gcd(n,m);
else
return gcd(n, m % n);
}
/* Driver program */
public static void main(String[] args)
{
int l = 2, b = 4, h = 6;
maximizecube(l, b, h);
}
}
Python3
143
Chapter 19. Divide cuboid into cubes such that sum of volumes is maximum
print(side, num)
# Driver code
l = 2
b = 4
h = 6
maximizecube(l, b, h)
C#
class GFG {
/* Driver program */
public static void Main()
{
144
Chapter 19. Divide cuboid into cubes such that sum of volumes is maximum
int l = 2, b = 4, h = 6;
maximizecube(l, b, h);
}
}
PHP
<?php
// PHP program to find optimal way
// to break cuboid into cubes.
// Recursive function to
// return gcd of a and b
function __gcd($a, $b)
{
// Everything divides 0
if($a == 0 or $b == 0)
return 0 ;
// base case
if($a == $b)
return $a ;
// a is greater
if($a > $b)
return __gcd($a - $b , $b ) ;
145
Chapter 19. Divide cuboid into cubes such that sum of volumes is maximum
// Driver code
$l = 2;
$b = 4;
$h = 6;
maximizecube($l, $b, $h);
Output:
2 6
Improved By : vt_m
Source
https://www.geeksforgeeks.org/divide-cuboid-cubes-sum-volumes-maximum/
146
Chapter 20
147
Chapter 20. Efficient Huffman Coding for Sorted Input Greedy Algo-4
148
Chapter 20. Efficient Huffman Coding for Sorted Input Greedy Algo-4
{
return queue->front == -1;
}
149
Chapter 20. Efficient Huffman Coding for Sorted Input Greedy Algo-4
// Step 3.c: Else, compare the front of two queues and dequeue minimum
if (getFront(firstQueue)->freq < getFront(secondQueue)->freq)
return deQueue(firstQueue);
return deQueue(secondQueue);
}
// Step 2:Create a leaf node for each unique character and Enqueue it to
// the first queue in non-decreasing order of frequency. Initially second
// queue is empty
for (int i = 0; i < size; ++i)
enQueue(firstQueue, newNode(data[i], freq[i]));
// Run while Queues contain more than one node. Finally, first queue will
// be empty and second queue will contain only one node
while (!(isEmpty(firstQueue) && isSizeOne(secondQueue)))
{
// Step 3: Dequeue two nodes with the minimum frequency by examining
// the front of both queues
left = findMin(firstQueue, secondQueue);
150
Chapter 20. Efficient Huffman Coding for Sorted Input Greedy Algo-4
// Step 4: Create a new internal node with frequency equal to the sum
// of the two nodes frequencies. Enqueue this node to second queue.
top = newNode('$' , left->freq + right->freq);
top->left = left;
top->right = right;
enQueue(secondQueue, top);
}
return deQueue(secondQueue);
}
// Prints huffman codes from the root of Huffman Tree. It uses arr[] to
// store codes
void printCodes(struct QueueNode* root, int arr[], int top)
{
// Assign 0 to left edge and recur
if (root->left)
{
arr[top] = 0;
printCodes(root->left, arr, top + 1);
}
// The main function that builds a Huffman Tree and print codes by traversing
// the built Huffman Tree
void HuffmanCodes(char data[], int freq[], int size)
{
// Construct Huffman Tree
struct QueueNode* root = buildHuffmanTree(data, freq, size);
151
Chapter 20. Efficient Huffman Coding for Sorted Input Greedy Algo-4
Output:
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111
Source
https://www.geeksforgeeks.org/efficient-huffman-coding-for-sorted-input-greedy-algo-4/
152
Chapter 21
1. Count cup, cdown, cleft and cright for U(Up), D(Down), L(Left) and R(Right) move-
ments respectively.
2. Calculate final_x = x + (cright – cleft) and final_y = y + (cdown – cup).
153
Chapter 21. Final cell position in the matrix
#include <bits/stdc++.h>
154
Chapter 21. Final cell position in the matrix
Java
class GFG
{
// function to find the
// final cell position
// in the given matrix
static void finalPos(String command, int n,
int x, int y)
{
// to count up, down, left
// and cright movements
int cup, cdown, cleft, cright;
155
Chapter 21. Final cell position in the matrix
// Driver Code
public static void main(String []args)
{
String command = "DDLRULL";
int n = command.length();
int x = 3, y = 4;
finalPos(command, n, x, y);
}
}
Output:
Source
https://www.geeksforgeeks.org/final-cell-position-in-the-matrix/
156
Chapter 22
Examples :
157
Chapter 22. Find element using minimum segments in Seven Segment Display
Input : arr[] = { 1, 2, 3, 4, 5 }.
Output : 1
1 uses on 2 segments to display.
Precompute the number of segment used by digits from 0 to 9 and store it. Now for each
element of the array sum the number of segment used by each digit. Then find the element
which is using the minimum number of segments.
The number of segment used by digit:
0 -> 6
1 -> 2
2 -> 5
3 -> 5
4 -> 4
5 -> 5
6 -> 6
7 -> 3
8 -> 7
9 -> 6
Below is the implementation of this approach:
C++
int count = 0;
158
Chapter 22. Find element using minimum segments in Seven Segment Display
return count;
}
return arr[minindex];
}
// Driven Program
int main()
{
int arr[] = {489, 206, 745, 123, 756};
int n = sizeof(arr)/sizeof(arr[0]);
cout << elementMinSegment(arr, n) << endl;
return 0;
}
Java
class GFG {
159
Chapter 22. Find element using minimum segments in Seven Segment Display
// used by digit 0 to 9.
static int []seg = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
int count = 0;
return count;
}
return arr[minindex];
}
// Driver program
160
Chapter 22. Find element using minimum segments in Seven Segment Display
C#
class GFG{
int count = 0;
return count;
}
161
Chapter 22. Find element using minimum segments in Seven Segment Display
return arr[minindex];
}
// Driver program
static public void Main()
{
int []arr = {489, 206, 745, 123, 756};
int n = arr.Length;
Console.WriteLine(elementMinSegment(arr, n));
}
}
PHP
<?php
// PHP program to find minimum
// number of segments required
$seg = array(6, 2, 5, 5, 4,
5, 6, 3, 7, 6);
162
Chapter 22. Find element using minimum segments in Seven Segment Display
return $seg[0];
$count = 0;
return $count;
}
return $arr[$minindex];
}
// Driver Code
$arr = array (489, 206, 745, 123, 756);
$n = sizeof($arr);
echo elementMinSegment($arr, $n) ,"\n";
163
Chapter 22. Find element using minimum segments in Seven Segment Display
Output :
745
Source
https://www.geeksforgeeks.org/find-element-using-minimum-segments-seven-segment-display/
164
Chapter 23
Find if k bookings possible with given arrival and departure times - GeeksforGeeks
A hotel manager has to process N advance bookings of rooms for the next season. His hotel
has K rooms. Bookings contain an arrival date and a departure date. He wants to find out
whether there are enough rooms in the hotel to satisfy the demand.
The idea is to sort the arrays and keep track of overlaps.
Examples:
Input : Arrivals : [1 3 5]
Departures : [2 6 8]
K : 1
Output : False
Hotel manager needs at least two
rooms as the second and third
intervals overlap.
The idea is store arrival and departure times in an auxiliary array with an additional marker
to indicate whether time is arrival or departure. Now sort the array. Process the sorted
array, for every arrival increment active bookings. And for every departure, decrement.
Keep track of maximum active bookings. If count of active bookings at any moment is more
than k, then return false. Else return return true.
Below is the c++ code for above approach.
#include <bits/stdc++.h>
165
Chapter 23. Find if k bookings possible with given arrival and departure times
int main()
{
int arrival[] = { 1, 3, 5 };
int departure[] = { 2, 6, 8 };
int n = sizeof(arrival) / sizeof(arrival[0]);
cout << (areBookingsPossible(arrival,
166
Chapter 23. Find if k bookings possible with given arrival and departure times
Output:
No
Source
https://www.geeksforgeeks.org/find-k-bookings-possible-given-arrival-departure-times/
167
Chapter 24
Input: a1[] = { 2, 3, 4 }
a2[] = { 1, 6, 5, 8 }
k = 4
Output: [1, 2] [1, 3] [1, 4] [2, 6]
• The idea is to maintain two pointers, one pointer pointing to one pair in (a1, a2) and
other in (a2, a1). Each time, compare the sums of the elements pointed by the two
168
Chapter 24. Find k pairs with smallest sums in two arrays Set 2
pairs and print the minimum one. After this, increment the pointer to the element in
the printed pair which was larger than the other. This helps to get the next possible
k smallest pair.
• Once the pointer has been updated to the element such that it starts pointing to the
first element of the array again, update the other pointer to the next value. This
update is done cyclically.
• Also, when both the pairs are pointing to the same element, update pointers in both
the pairs so as to avoid extra pair’s printing. Update one pair’s pointer according to
rule1 and other’s opposite to rule1. This is done to ensure that all the permutations
are considered and no repetitions of pairs are there.
• print [1, 2]
• print [1, 4]
169
Chapter 24. Find k pairs with smallest sums in two arrays Set 2
int cnt = 0;
170
Chapter 24. Find k pairs with smallest sums in two arrays Set 2
171
Chapter 24. Find k pairs with smallest sums in two arrays Set 2
// Driver Code
int main()
{
int a1[] = { 2, 3, 4 };
int a2[] = { 1, 6, 5, 8 };
int size1 = sizeof(a1) / sizeof(a1[0]);
int size2 = sizeof(a2) / sizeof(a2[0]);
int k = 4;
printKPairs(a1, a2, size1, size2, k);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-k-pairs-with-smallest-sums-in-two-arrays-set-2/
172
Chapter 25
Find maximum height pyramid from the given array of objects - GeeksforGeeks
Given n objects, with each object has width wi . We need to arrange them in a pyramidal
way such that :
173
Chapter 25. Find maximum height pyramid from the given array of objects
The task is to find the maximum height that can be achieved from given objects.
Examples :
The idea is to use greedy approach by placing the object with the lowest width at the top,
the next object at the level right below and so on.
To find the maximum number of levels, sort the given array and try to form pyramid from
top to bottom. Find the smallest element of array i.e first element of array after sorting,
place it on the top. Then try to build levels below it with greater number of objects and
greater width.
Below is the implementation of this approach:
C++
174
Chapter 25. Find maximum height pyramid from the given array of objects
int curr_count = 0;
return ans;
}
// Driver Program
int main()
{
int boxes[] = {10, 20, 30, 50, 60, 70};
int n = sizeof(boxes)/sizeof(boxes[0]);
cout << maxLevel(boxes, n) << endl;
return 0;
}
Java
175
Chapter 25. Find maximum height pyramid from the given array of objects
import java.util.Arrays;
class GFG {
176
Chapter 25. Find maximum height pyramid from the given array of objects
// Increment number of
// level.
ans++;
}
}
return ans;
}
// Driver Program
static public void main (String[] args)
{
int []boxes = {10, 20, 30, 50, 60, 70};
int n = boxes.length;
System.out.println(maxLevel(boxes, n));
}
}
Python 3
177
Chapter 25. Find maximum height pyramid from the given array of objects
# Number of object in
# current level.
curr_count = 0
# Driver Code
if __name__ == "__main__":
boxes= [10, 20, 30, 50, 60, 70]
n = len(boxes)
print(maxLevel(boxes, n))
C#
178
Chapter 25. Find maximum height pyramid from the given array of objects
179
Chapter 25. Find maximum height pyramid from the given array of objects
// Increment number of
// level.
ans++;
}
}
return ans;
}
// Driver Program
static public void Main ()
{
int []boxes = {10, 20, 30, 50, 60, 70};
int n = boxes.Length;
Console.WriteLine(maxLevel(boxes, n));
}
}
PHP
<?php
// PHP program to find maximum
// height pyramid from the
// given object width.
// Initialize result
$ans = 1;
180
Chapter 25. Find maximum height pyramid from the given array of objects
// Number of object
// in current level.
$curr_count = 0;
// Driver Code
$boxes = array(10, 20, 30, 50, 60, 70);
$n = count($boxes);
echo maxLevel($boxes, $n) ;
181
Chapter 25. Find maximum height pyramid from the given array of objects
?>
Output :
Source
https://www.geeksforgeeks.org/find-maximum-height-pyramid-from-the-given-array-of-objects/
182
Chapter 26
183
Chapter 26. Find maximum sum possible equal sum of three stacks
The idea is to compare the sum of each stack, if they are not same, remove the top element
of the stack having the maximum sum.
Algorithm for solving this problem:
2. If the sum of all three stacks is same, then this is the maximum sum.
3. Else remove the top element of the stack having the maximum sum among three of
stacks. Repeat step 1 and step 2.
The approach works because elements are positive. To make sum equal, we must remove
some element from stack having more sum and we can only remove from top.
Below is the implementation of this approach:
C/C++
184
Chapter 26. Find maximum sum possible equal sum of three stacks
// Driven Program
int main()
{
int stack1[] = { 3, 2, 1, 1, 1 };
185
Chapter 26. Find maximum sum possible equal sum of three stacks
int stack2[] = { 4, 3, 2 };
int stack3[] = { 1, 1, 4, 1 };
int n1 = sizeof(stack1)/sizeof(stack1[0]);
int n2 = sizeof(stack2)/sizeof(stack2[0]);
int n3 = sizeof(stack3)/sizeof(stack3[0]);
cout << maxSum(stack1, stack2, stack3, n1, n2, n3) << endl;
return 0;
}
Java
186
Chapter 26. Find maximum sum possible equal sum of three stacks
int n1 = stack1.length;
int n2 = stack2.length;
int n3 = stack3.length;
System.out.println(maxSum(stack1, stack2,
stack3, n1, n2, n3));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python
187
Chapter 26. Find maximum sum possible equal sum of three stacks
# Driven Program
stack1 = [ 3, 2, 1, 1, 1 ]
stack2 = [ 4, 3, 2 ]
stack3 = [ 1, 1, 4, 1 ]
n1 = len(stack1)
n2 = len(stack2)
n3 = len(stack3)
C#
188
Chapter 26. Find maximum sum possible equal sum of three stacks
class GFG {
while (true) {
189
Chapter 26. Find maximum sum possible equal sum of three stacks
sum2 -= stack2[top2++];
else if (sum3 >= sum2 && sum3 >= sum1)
sum3 -= stack3[top3++];
}
}
int n1 = stack1.Length;
int n2 = stack2.Length;
int n3 = stack3.Length;
Console.Write(maxSum(stack1, stack2,
stack3, n1, n2, n3));
}
}
PHP
<?php
// PHP program to calculate maximum
// sum with equal stack sum.
190
Chapter 26. Find maximum sum possible equal sum of three stacks
// As given in question,
// first element is top
// of stack..
$top1 =0;
$top2 = 0;
$top3 = 0;
$ans = 0;
while (1)
{
// Driver Code
$stack1 = array(3, 2, 1, 1, 1);
$stack2 = array(4, 3, 2);
$stack3 = array(1, 1, 4, 1);
$n1 = sizeof($stack1);
$n2 = sizeof($stack2);
$n3 = sizeof($stack3);
echo maxSum($stack1, $stack2,
$stack3, $n1,
$n2, $n3) ;
191
Chapter 26. Find maximum sum possible equal sum of three stacks
Output:
Time Complexity : O(n1 + n2 + n3) where n1, n2 and n3 are sizes of three stacks.
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/find-maximum-sum-possible-equal-sum-three-stacks/
192
Chapter 27
Find minimum number of currency notes and values that sum to given amount - Geeks-
forGeeks
Given an amount, find the minimum number of notes of different denominations that sum
upto the given amount. Starting from the highest denomination note, try to accommodate
as many notes possible for given amount.
We may assume that we have infinite supply of notes of values {2000, 500, 200, 100, 50, 20,
10, 5, 1}
Examples:
Input : 800
Output : Currency Count
500 : 1
200 : 1
100 : 1
Input : 2456
Output : Currency Count
2000 : 1
200 : 2
50 : 1
5 : 1
1 : 1
This problem is a simple variation of coin change problem. Here Greedy approach works as
given system is canonical (Please refer this and this for details)
193
Chapter 27. Find minimum number of currency notes and values that sum to given
amount
// Print notes
cout << "Currency Count ->" << endl;
for (int i = 0; i < 9; i++) {
if (noteCounter[i] != 0) {
cout << notes[i] << " : "
<< noteCounter[i] << endl;
}
}
}
// Driver function
int main()
{
int amount = 868;
countCurrency(amount);
return 0;
}
Python3
194
Chapter 27. Find minimum number of currency notes and values that sum to given
amount
noteCounter = [0, 0, 0, 0, 0,
0, 0, 0, 0]
# Driver code
amount = 868
countCurrency(amount)
Java
// Print notes
System.out.println("Currency Count ->");
195
Chapter 27. Find minimum number of currency notes and values that sum to given
amount
// driver function
public static void main(String argc[]){
int amount = 868;
countCurrency(amount);
}
C#
// Print notes
Console.WriteLine("Currency Count ->");
for (int i = 0; i < 9; i++) {
if (noteCounter[i] != 0) {
Console.WriteLine(notes[i] + " : "
+ noteCounter[i]);
}
}
196
Chapter 27. Find minimum number of currency notes and values that sum to given
amount
// Driver function
public static void Main(){
int amount = 868;
countCurrency(amount);
}
PHP
<?php
// PHP program to accept an amount
// and count number of notes
197
Chapter 27. Find minimum number of currency notes and values that sum to given
amount
$noteCounter[$i] . "\n");
}
}
}
// Driver Code
$amount = 868;
countCurrency($amount);
Output:
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/find-number-currency-notes-sum-upto-given-amount/
198
Chapter 28
Find minimum time to finish all jobs with given constraints - GeeksforGeeks
Given an array of jobs with different time requirements. There are K identical assignees
available and we are also given how much time an assignee takes to do one unit of the job.
Find the minimum time to finish all jobs with following constraints.
• An assignee can be assigned only contiguous jobs. For example, an assignee cannot
be assigned jobs 1 and 3, but not 2.
• Two assignees cannot share (or co-assigned) a job, i.e., a job cannot be partially
assigned to one assignee and partially to other.
Input :
Examples :
199
Chapter 28. Find minimum time to finish all jobs with given constraints
assignee.
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to use Binary Search. Think if we have a function (say isPossible()) that tells us
if it’s possible to finish all jobs within a given time and number of available assignees. We
can solve this problem by doing a binary search for the answer. If the middle point of binary
search is not possible, then search in second half, else search in first half. Lower bound for
Binary Search for minimum time can be set as 0. The upper bound can be obtained by
adding all given job times.
Now how to implement isPossible()? This function can be implemented using Greedy Ap-
proach. Since we want to know if it is possible to finish all jobs within a given time, we
traverse through all jobs and keep assigning jobs to current assignee one by one while a
job can be assigned within the given time limit. When time taken by current assignee ex-
ceeds the given time, create a new assignee and start assigning jobs to it. If the number of
assignees becomes more than k, then return false, else return true.
C++
200
Chapter 28. Find minimum time to finish all jobs with given constraints
{
// If time assigned to current assignee exceeds max,
// increment count of assignees.
if (curr_time + job[i] > time) {
curr_time = 0;
cnt++;
}
else { // Else add time of job to current time and move
// to next job.
curr_time += job[i];
i++;
}
}
201
Chapter 28. Find minimum time to finish all jobs with given constraints
// Driver program
int main()
{
int job[] = {10, 7, 8, 12, 6, 8};
int n = sizeof(job)/sizeof(job[0]);
int k = 4, T = 5;
cout << findMinTime(k, T, job, n) << endl;
return 0;
}
Java
class GFG
{
// Utility function to get
// maximum element in job[0..n-1]
static int getMax(int arr[], int n)
{
int result = arr[0];
for (int i=1; i<n; i++)
if (arr[i] > result)
result = arr[i];
return result;
}
202
Chapter 28. Find minimum time to finish all jobs with given constraints
// Initialize answer
int ans = end;
203
Chapter 28. Find minimum time to finish all jobs with given constraints
{
// Update answer
ans = Math.min(ans, mid);
end = mid - 1;
}
else
start = mid + 1;
}
// Driver program
public static void main(String arg[])
{
int job[] = {10, 7, 8, 12, 6, 8};
int n = job.length;
int k = 4, T = 5;
System.out.println(findMinTime(k, T, job, n));
}
}
C#
class GFG
{
// Utility function to get
// maximum element in job[0..n-1]
static int getMax(int []arr, int n)
{
int result = arr[0];
for (int i=1; i<n; i++)
if (arr[i] > result)
result = arr[i];
return result;
}
204
Chapter 28. Find minimum time to finish all jobs with given constraints
// Initialize answer
int ans = end;
205
Chapter 28. Find minimum time to finish all jobs with given constraints
end = mid - 1;
}
else
start = mid + 1;
}
// Driver program
public static void Main()
{
int []job = {10, 7, 8, 12, 6, 8};
int n = job.Length;
int k = 4, T = 5;
Console.WriteLine(findMinTime(k, T, job, n));
}
}
Output:
75
206
Chapter 28. Find minimum time to finish all jobs with given constraints
Source
https://www.geeksforgeeks.org/find-minimum-time-to-finish-all-jobs-with-given-constraints/
207
Chapter 29
Find smallest number with given number of digits and sum of digits - GeeksforGeeks
How to find the smallest number with given digit sum s and number of digits d?
Examples :
Input : s = 9, d = 2
Output : 18
There are many other possible numbers
like 45, 54, 90, etc with sum of digits
as 9 and number of digits as 2. The
smallest of them is 18.
Input : s = 20, d = 3
Output : 299
A Simple Solution is to consider all m digit numbers and keep track of minimum number
with digit sum as s. A close upper bound on time complexity of this solution is O(10m ).
There is a Greedy approach to solve the problem. The idea is to one by one fill all digits
from rightmost to leftmost (or from least significant digit to most significant).
We initially deduct 1 from sum s so that we have smallest digit at the end. After deducting
1, we apply greedy approach. We compare remaining sum with 9, if remaining sum is more
than 9, we put 9 at the current position, else we put the remaining sum. Since we fill digits
from right to left, we put the highest digits on the right side. Below is implementation of
the idea.
C++
208
Chapter 29. Find smallest number with given number of digits and sum of digits
209
Chapter 29. Find smallest number with given number of digits and sum of digits
// Driver code
int main()
{
int s = 9, m = 2;
findSmallest(m, s);
return 0;
}
Java
class GFG
{
// Function to print the smallest possible number with digit sum 's'
// and 'm' number of digits
static void findSmallest(int m, int s)
{
// If sum of digits is 0, then a number is possible
// only if number of digits is 1
if (s == 0)
{
System.out.print(m == 1 ? "Smallest number is 0" : "Not possible");
return ;
}
210
Chapter 29. Find smallest number with given number of digits and sum of digits
// driver program
public static void main (String[] args)
{
int s = 9, m = 2;
findSmallest(m, s);
}
}
Python3
211
Chapter 29. Find smallest number with given number of digits and sum of digits
def findSmallest(m,s):
# If sum of digits is 0,
# then a number is possible
# only if number of digits is 1.
if (s == 0):
if(m == 1) :
print("Smallest number is 0")
else :
print("Not possible")
return
print("Not possible")
return
# Create an array to
# store digits of result
res=[0 for i in range(m+1)]
res[i] = 9
s -= 9
else:
res[i] = s
s = 0
212
Chapter 29. Find smallest number with given number of digits and sum of digits
s = 9
m = 2
findSmallest(m, s)
C#
class GFG
{
// Function to print the smallest
// possible number with digit sum 's'
// and 'm' number of digits
static void findSmallest(int m, int s)
{
// If sum of digits is 0,
// then a number is possible
// only if number of digits is 1
if (s == 0)
{
Console.Write(m == 1 ?
"Smallest number is 0" :
"Not possible");
return ;
}
213
Chapter 29. Find smallest number with given number of digits and sum of digits
// Create an array to
// store digits of result
int []res = new int[m];
214
Chapter 29. Find smallest number with given number of digits and sum of digits
// Driver Code
public static void Main ()
{
int s = 9, m = 2;
findSmallest(m, s);
}
}
PHP
<?php
// PHP program to find the smallest
// number that can be formed from
// given sum of digits and number
// of digits.
215
Chapter 29. Find smallest number with given number of digits and sum of digits
// Driver code
$s = 9; $m = 2;
findSmallest($m, $s);
Output :
Smallest number is 18
216
Chapter 29. Find smallest number with given number of digits and sum of digits
We will soon be discussing approach to find the largest possible number with given sum of
digits and number of digits.
Improved By : nitin mittal, jit_t
Source
https://www.geeksforgeeks.org/find-smallest-number-with-given-number-of-digits-and-digit-sum/
217
Chapter 30
Find the Largest Cube formed by Deleting minimum Digits from a number - GeeksforGeeks
Given a number n, the task is to find the largest perfect cube that can be formed by deleting
minimum digits(possibly 0) from the number.
X is called a perfect cube if X = Y3 for some Y.
Examples:
Input : 4125
Output : 125
Explanation
125 = 53. We can form 125 by deleting digit 4 from 4125
Input : 876
Output :8
Explanation
8 = 23. We can form 8 by deleting digits 7 and 6 from 876
We can generate cubes of all numbers till from 1 to N1/3 (We don’t consider 0 as 0 is not
considered as a perfect cube). We iterate the cubes from largest to the smallest.
Now if we look at the number n given to us, then we know that this number contains only
log(n) + 1 digits, thus we can efficiently approach the problem if we treat this number n as
a string hereafter.
While iterating on the perfect cubes, we check if the perfect cube is a subsequence of the
number n when its represented as a string.If this is the case then the deletions required for
changing the number n to the current perfect cube is:
218
Chapter 30. Find the Largest Cube formed by Deleting minimum Digits from a number
Since we want the largest cube number we traverse the array of preprocessed cubes in reverse
order.
219
Chapter 30. Find the Largest Cube formed by Deleting minimum Digits from a number
if (digitsInCube == index)
return currCube;
}
}
// Driver Code
int main()
{
long long int n;
n = 4125;
findLargestCube(n);
n = 876;
findLargestCube(n);
return 0;
}
Output:
220
Chapter 30. Find the Largest Cube formed by Deleting minimum Digits from a number
Time Complexity of the above algorithm is O(N1/3 log(N) log(N) is due to the fact that the
number of digits in N are Log(N) + 1.
Source
https://www.geeksforgeeks.org/find-largest-cube-formed-deleting-minimum-digits-number/
221
Chapter 31
Find the Largest number with given number of digits and sum of digits - GeeksforGeeks
How to find the largest number with given digit sum s and number of digits d?
Examples:
Input : s = 9, d = 2
Output : 90
Input : s = 20, d = 3
Output : 992
A Simple Solution is to consider all m digit numbers and keep track of maximum number
with digit sum as s. A close upper bound on time complexity of this solution is O(10m ).
There is a Greedy approach to solve the problem. The idea is to one by one fill all digits
from leftmost to rightmost (or from most significant digit to least significant).
We compare remaining sum with 9, if remaining sum is more than 9, we put 9 at the current
position, else we put the remaining sum. Since we fill digits from left to right, we put the
highest digits on the left side, hence get the largest number. Below is implementation of the
idea.
C++
222
Chapter 31. Find the Largest number with given number of digits and sum of digits
223
Chapter 31. Find the Largest number with given number of digits and sum of digits
// Driver code
int main()
{
int s = 9, m = 2;
findLargest(m, s);
return 0;
}
Java
class GFG
{
// Function to print the largest possible number with digit sum 's'
// and 'm' number of digits
static void findLargest(int m, int s)
{
// If sum of digits is 0, then a number is possible
// only if number of digits is 1
if (s == 0)
{
System.out.print(m == 1 ? "Largest number is 0" : "Not possible");
return ;
}
224
Chapter 31. Find the Largest number with given number of digits and sum of digits
s -= 9;
}
// driver program
public static void main (String[] args)
{
int s = 9, m = 2;
findLargest(m, s);
}
}
Python3
# If sum of digits is 0,
# then a nuber is possible
# only if number of digits
# is 1.
if (s == 0) :
225
Chapter 31. Find the Largest number with given number of digits and sum of digits
if(m == 1) :
print("Largest number is " , "0",end = "")
else :
print("Not possible",end = "")
return
# Create an array to
# store digits of
# result
res = [0] * m
# If remaining sum
# becomes less than
# 9, then fill the
# remaining sum
else :
res[i] = s
s = 0
for i in range(0, m) :
print(res[i],end = "")
# Driver code
s = 9
m = 2
findLargest(m, s)
226
Chapter 31. Find the Largest number with given number of digits and sum of digits
C#
class GFG
{
return ;
}
// Create an array to
// store digits of result
int []res = new int[m];
227
Chapter 31. Find the Largest number with given number of digits and sum of digits
// Driver Code
static public void Main ()
{
int s = 9, m = 2;
findLargest(m, s);
}
}
PHP
<?php
// PHP program to find the largest
// number that can be formed from
// given sum of digits and number
// of digits.
228
Chapter 31. Find the Largest number with given number of digits and sum of digits
if ($s == 0)
{
if(($m == 1) == true)
echo "Largest number is " , 0;
else
echo "Not possible";
return ;
}
// Driver code
$s = 9; $m = 2;
229
Chapter 31. Find the Largest number with given number of digits and sum of digits
findLargest($m, $s);
Output :
Largest number is 90
Source
https://www.geeksforgeeks.org/find-the-largest-number-with-given-number-of-digits-and-sum-of-digits/
230
Chapter 32
Find the minimum and maximum amount to buy all N candies - GeeksforGeeks
In a candy store there are N different types of candies available and the prices of all the
N different types of candies are provided. There is also an attractive offer by candy store.
We can buy a single candy from the store and get at-most K other candies (all are different
types) for free.
1. Find minimum amount of money we have to spend to buy all the N different candies.
2. Find maximum amount of money we have to spend to buy all the N different candies.
In both the cases we must utilize the offer and get maximum possible candies back. If k or
more candies are available, we must take k candies for every candy purchase. If less than k
candies are available, we must take all candies for a candy purchase.
Examples:
231
Chapter 32. Find the minimum and maximum amount to buy all N candies
One important thing to note is, we must use the offer and get maximum candies back
for every candy purchase. So if we want to minimize the money, we must buy candies of
minimum cost and get candies of maximum costs for free. To maximize the money, we must
do reverse. Below is algorithm based on this.
C++
232
Chapter 32. Find the minimum and maximum amount to buy all N candies
// Driver code
int main()
{
int arr[] = {3, 2, 1, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
sort(arr, arr+n);
Java
class GFG {
233
Chapter 32. Find the minimum and maximum amount to buy all N candies
// Driver code
public static void main(String[] args)
{
int arr[] = { 3, 2, 1, 4 };
int n = arr.length;
int k = 2;
Arrays.sort(arr);
System.out.println(findMinimum(arr, n, k) +
" " + findMaximum(arr, n, k));
}
}
Python3
# Python implementation
# to find the minimum
# and maximum amount
# Function to find
234
Chapter 32. Find the minimum and maximum amount to buy all N candies
res = 0
i=0
while(n):
# And take k
# candies for free
# from the last
n = n-k
i+=1
return res
# Function to find
# the maximum amount
# to buy all candies
def findMaximum(arr, n, k):
res = 0
index = 0
i=n-1
while(i>=index):
return res
# Driver code
arr = [3, 2, 1, 4]
n = len(arr)
k = 2
arr.sort()
235
Chapter 32. Find the minimum and maximum amount to buy all N candies
C#
return res;
}
236
Chapter 32. Find the minimum and maximum amount to buy all N candies
return res;
}
// Driver code
public static void Main()
{
int []arr = { 3, 2, 1, 4 };
int n = arr.Length;
int k = 2;
Array.Sort(arr);
Console.WriteLine(
findMinimum(arr, n, k) + " "
+ findMaximum(arr, n, k));
}
}
PHP
<?php
// PHP implementation to find the minimum
// and maximum amount
237
Chapter 32. Find the minimum and maximum amount to buy all N candies
// Driver Code
$arr = array(3, 2, 1, 4);
$n = sizeof($arr);
$k = 2;
sort($arr); sort($arr,$n);
Output:
3 7
Source
https://www.geeksforgeeks.org/find-minimum-maximum-amount-buy-n-candies/
238
Chapter 33
Input : w = 24 m = 3 n = 5
Output : 3 3 0
We use three units of both shelves
and 0 space is left.
3 * 3 + 3 * 5 = 24
So empty space = 24 - 24 = 0
Another solution could have been 8 0 0
but since the larger shelf of length 5
is cheaper the former will be the answer.
Input : w = 29 m = 3 n = 9
Output : 0 3 2
0 * 3 + 3 * 9 = 27
29 - 27 = 2
A simple and efficient approach will be to try all possible combinations of shelves that fit
within the length of the wall.
To implement this approach along with the constraint that larger shelf costs less than the
smaller one, starting from 0, we increase no of larger type shelves till they can be fit. For
each case we calculate the empty space and finally store that value which minimizes the
empty space. if empty space is same in two cases we prefer the one with more no of larger
shelves. Below is its implementation.
C++
239
Chapter 33. Fitting Shelves Problem
cout << num_m << " " << num_n << " "
<< min_empty << endl;
}
// Driver code
int main()
{
int wall = 24, m = 3, n = 5;
minSpacePreferLarge(wall, m, n);
return 0;
}
Java
240
Chapter 33. Fitting Shelves Problem
Python
241
Chapter 33. Fitting Shelves Problem
# Driver code
w = 24
m = 3
n = 5
minSpacePreferLarge(w, m, n)
Output:
3 3 0
Source
https://www.geeksforgeeks.org/fitting-shelves-problem/
242
Chapter 34
Input:
Items as (value, weight) pairs
arr[] = {{60, 10}, {100, 20}, {120, 30}}
Knapsack Capacity, W = 50;
Output:
Maximum possible value = 220
by taking items of weight 20 and 30 kg
In Fractional Knapsack, we can break items for maximizing the total value of knapsack.
This problem in which we can break an item is also called the fractional knapsack problem.
Input :
Same as above
Output :
Maximum possible value = 240
By taking full items of 10 kg, 20 kg and
2/3rd of last item of 30 kg
A brute-force solution would be to try all possible subset with all different fraction but
that will be too much time taking.
An efficient solution is to use Greedy approach. The basic idea of the greedy approach
is to calculate the ratio value/weight for each item and sort the item on basis of this ratio.
243
Chapter 34. Fractional Knapsack Problem
Then take the item with the highest ratio and add them until we can’t add the next item
as a whole and at the end add the next item as much as we can. Which will always be the
optimal solution to this problem.
A simple code with our own comparison function can be written as follows, please see sort
function more closely, the third argument to sort function is our comparison function which
sorts the item according to value/weight ratio in non-decreasing order.
After sorting we need to loop over these items and add them in our knapsack satisfying
above-mentioned criteria.
// Constructor
Item(int value, int weight) : value(value), weight(weight)
{}
};
244
Chapter 34. Fractional Knapsack Problem
Output :
As main time taking step is sorting, the whole problem can be solved in O(n log n) only.
This article is contributed by Utkarsh Trivedi.
Source
https://www.geeksforgeeks.org/fractional-knapsack-problem/
245
Chapter 35
Following are C++ and Java implementations of the above Greedy Algorithm.
C++
246
Chapter 35. Graph Coloring Set 2 (Greedy Algorithm)
{
int V; // No. of vertices
list<int> *adj; // A dynamic array of adjacency lists
public:
// Constructor and destructor
Graph(int V) { this->V = V; adj = new list<int>[V]; }
~Graph() { delete [] adj; }
247
Chapter 35. Graph Coloring Set 2 (Greedy Algorithm)
if (result[*i] != -1)
available[result[*i]] = true;
Graph g2(5);
g2.addEdge(0, 1);
g2.addEdge(0, 2);
g2.addEdge(1, 2);
g2.addEdge(1, 4);
g2.addEdge(2, 4);
g2.addEdge(4, 3);
cout << "\nColoring of graph 2 \n";
g2.greedyColoring();
return 0;
}
248
Chapter 35. Graph Coloring Set 2 (Greedy Algorithm)
Java
//Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
249
Chapter 35. Graph Coloring Set 2 (Greedy Algorithm)
// Driver method
public static void main(String args[])
{
Graph g1 = new Graph(5);
g1.addEdge(0, 1);
g1.addEdge(0, 2);
g1.addEdge(1, 2);
g1.addEdge(1, 3);
g1.addEdge(2, 3);
g1.addEdge(3, 4);
System.out.println("Coloring of graph 1");
g1.greedyColoring();
System.out.println();
Graph g2 = new Graph(5);
250
Chapter 35. Graph Coloring Set 2 (Greedy Algorithm)
g2.addEdge(0, 1);
g2.addEdge(0, 2);
g2.addEdge(1, 2);
g2.addEdge(1, 4);
g2.addEdge(2, 4);
g2.addEdge(4, 3);
System.out.println("Coloring of graph 2 ");
g2.greedyColoring();
}
}
// This code is contributed by Aakash Hasija
Output:
Coloring of graph 1
Vertex 0 ---> Color 0
Vertex 1 ---> Color 1
Vertex 2 ---> Color 2
Vertex 3 ---> Color 0
Vertex 4 ---> Color 1
Coloring of graph 2
Vertex 0 ---> Color 0
Vertex 1 ---> Color 1
Vertex 2 ---> Color 2
Vertex 3 ---> Color 0
Vertex 4 ---> Color 3
251
Chapter 35. Graph Coloring Set 2 (Greedy Algorithm)
So the order in which the vertices are picked is important. Many people have sug-
gested different ways to find an ordering that work better than the basic algorithm
on average. The most common is Welsh–Powell Algorithm which considers vertices in
descending order of degrees.
How does the basic algorithm guarantee an upper bound of d+1?
Here d is the maximum degree in the given graph. Since d is maximum degree, a vertex
cannot be attached to more than d vertices. When we color a vertex, at most d colors could
have already been used by its adjacent. To color this vertex, we need to pick the smallest
numbered color that is not used by the adjacent vertices. If colors are numbered like 1, 2,
…., then the value of such smallest number must be between 1 to d+1 (Note that d numbers
are already picked by adjacent vertices).
252
Chapter 35. Graph Coloring Set 2 (Greedy Algorithm)
This can also be proved using induction. See thisvideo lecture for proof.
We will soon be discussing some interesting facts about chromatic number and graph color-
ing.
Improved By : ChamanJhinga
Source
https://www.geeksforgeeks.org/graph-coloring-set-2-greedy-algorithm/
253
Chapter 36
We can generate Egyptian Fractions using Greedy Algorithm. For a given number of the
form ‘nr/dr’ where dr > nr, first find the greatest possible unit fraction, then recur for the
remaining part. For example, consider 6/14, we first find ceiling of 14/6, i.e., 3. So the first
unit fraction becomes 1/3, then recur for (6/14 – 1/3) i.e., 4/42.
Below is implementation of above idea.
C++
254
Chapter 36. Greedy Algorithm for Egyptian Fraction
if (dr == 0 || nr == 0)
return;
// Driver Program
int main()
{
int nr = 6, dr = 14;
cout << "Egyptian Fraction Representation of "
<< nr << "/" << dr << " is\n ";
printEgyptian(nr, dr);
return 0;
}
Output:
255
Chapter 36. Greedy Algorithm for Egyptian Fraction
The Greedy algorithm works because a fraction is always reduced to a form where denomina-
tor is greater than numerator and numerator doesn’t divide denominator. For such reduced
forms, the highlighted recursive call is made for reduced numerator. So the recursive calls
keep on reducing the numerator till it reaches 1.
References:
http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fractions/egyptian.html
This article is contributed by Shubham. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : DhruvitJakasaniya
Source
https://www.geeksforgeeks.org/greedy-algorithm-egyptian-fraction/
256
Chapter 37
Input: V = 70
Output: 2
We need a 50 Rs note and a 20 Rs note.
Input: V = 121
Output: 3
We need a 100 Rs note, a 20 Rs note and a
1 Rs coin.
The idea is simple Greedy Algorithm. Start from largest possible denomination and keep
adding denominations while remaining value is greater than 0. Below is complete algorithm.
257
Chapter 37. Greedy Algorithm to find Minimum number of Coins
// Driver program
void findMin(int V)
{
// Initialize result
vector<int> ans;
// Print result
for (int i = 0; i < ans.size(); i++)
cout << ans[i] << " ";
}
// Driver program
int main()
{
int n = 93;
cout << "Following is minimal number of change for " << n << " is ";
findMin(n);
return 0;
}
Output:
Note that above approach may not work for all denominations. For example, it doesn’t
work for denominations {9, 6, 5, 1} and V = 11. The above approach would print 9, 1 and
258
Chapter 37. Greedy Algorithm to find Minimum number of Coins
Source
https://www.geeksforgeeks.org/greedy-algorithm-to-find-minimum-number-of-coins/
259
Chapter 38
260
Chapter 38. Huffman Coding Greedy Algo-3
4. Repeat steps#2 and #3 until the heap contains only one node. The remaining node is
the root node and the tree is complete.
Let us understand the algorithm with an example:
character Frequency
a 5
b 9
c 12
d 13
e 16
f 45
Step 1. Build a min heap that contains 6 nodes where each node represents root of a tree
with single node.
Step 2 Extract two minimum frequency nodes from min heap. Add a new internal node
with frequency 5 + 9 = 14.
Now min heap contains 5 nodes where 4 nodes are roots of trees with single element each,
and one heap node is root of tree with 3 elements
character Frequency
c 12
d 13
Internal Node 14
e 16
f 45
Step 3: Extract two minimum frequency nodes from heap. Add a new internal node with
frequency 12 + 13 = 25
Now min heap contains 4 nodes where 2 nodes are roots of trees with single element each,
and two heap nodes are root of tree with more than one nodes.
character Frequency
261
Chapter 38. Huffman Coding Greedy Algo-3
Internal Node 14
e 16
Internal Node 25
f 45
Step 4: Extract two minimum frequency nodes. Add a new internal node with frequency
14 + 16 = 30
character Frequency
Internal Node 25
Internal Node 30
f 45
Step 5: Extract two minimum frequency nodes. Add a new internal node with frequency
25 + 30 = 55
character Frequency
f 45
Internal Node 55
Step 6: Extract two minimum frequency nodes. Add a new internal node with frequency
45 + 55 = 100
262
Chapter 38. Huffman Coding Greedy Algo-3
character Frequency
Internal Node 100
Since the heap contains only one node, the algorithm stops here.
Steps to print codes from Huffman Tree:
Traverse the tree formed starting from the root. Maintain an auxiliary array. While moving
to the left child, write 0 to the array. While moving to the right child, write 1 to the array.
Print the array when a leaf node is encountered.
character code-word
f 0
c 100
d 101
a 1100
b 1101
e 111
263
Chapter 38. Huffman Coding Greedy Algo-3
264
Chapter 38. Huffman Coding Greedy Algo-3
return temp;
}
// current size is 0
minHeap->size = 0;
minHeap->capacity = capacity;
minHeap->array
= (struct MinHeapNode**)malloc(minHeap->
capacity * sizeof(struct MinHeapNode*));
return minHeap;
}
// A utility function to
// swap two min heap nodes
void swapMinHeapNode(struct MinHeapNode** a,
struct MinHeapNode** b)
265
Chapter 38. Huffman Coding Greedy Algo-3
if (smallest != idx) {
swapMinHeapNode(&minHeap->array[smallest],
&minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
--minHeap->size;
minHeapify(minHeap, 0);
return temp;
}
++minHeap->size;
int i = minHeap->size - 1;
266
Chapter 38. Huffman Coding Greedy Algo-3
i = (i - 1) / 2;
}
minHeap->array[i] = minHeapNode;
}
int n = minHeap->size - 1;
int i;
printf("\n");
}
267
Chapter 38. Huffman Coding Greedy Algo-3
minHeap->size = size;
buildMinHeap(minHeap);
return minHeap;
}
{
struct MinHeapNode *left, *right, *top;
top->left = left;
top->right = right;
insertMinHeap(minHeap, top);
}
268
Chapter 38. Huffman Coding Greedy Algo-3
arr[top] = 0;
printCodes(root->left, arr, top + 1);
}
arr[top] = 1;
printCodes(root->right, arr, top + 1);
}
{
// Construct Huffman Tree
struct MinHeapNode* root
= buildHuffmanTree(data, freq, size);
269
Chapter 38. Huffman Coding Greedy Algo-3
return 0;
}
// For comparison of
// two heap nodes (needed in min heap)
struct compare {
{
return (l->freq > r->freq);
270
Chapter 38. Huffman Coding Greedy Algo-3
}
};
if (!root)
return;
if (root->data != '$')
cout << root->data << ": " << str << "\n";
right = minHeap.top();
minHeap.pop();
271
Chapter 38. Huffman Coding Greedy Algo-3
top->left = left;
top->right = right;
minHeap.push(top);
}
return 0;
}
Java
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Comparator;
int data;
char c;
HuffmanNode left;
HuffmanNode right;
}
272
Chapter 38. Huffman Coding Greedy Algo-3
return;
}
// main function
public static void main(String[] args)
{
273
Chapter 38. Huffman Coding Greedy Algo-3
// number of characters.
int n = 6;
char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' };
int[] charfreq = { 5, 9, 12, 13, 16, 45 };
hn.c = charArray[i];
hn.data = charfreq[i];
hn.left = null;
hn.right = null;
274
Chapter 38. Huffman Coding Greedy Algo-3
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111
Time complexity: O(nlogn) where n is the number of unique characters. If there are n
nodes, extractMin() is called 2*(n – 1) times. extractMin() takes O(logn) time as it calles
minHeapify(). So, overall complexity is O(nlogn).
If the input array is sorted, there exists a linear time algorithm. We will soon be discussing
in our next post.
Reference:
http://en.wikipedia.org/wiki/Huffman_coding
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please
write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.
Improved By : kddeepak
275
Chapter 38. Huffman Coding Greedy Algo-3
Source
https://www.geeksforgeeks.org/huffman-coding-greedy-algo-3/
276
Chapter 39
Huffman Decoding
277
Chapter 39. Huffman Decoding
To decode the encoded data we require the Huffman tree. We iterate through the binary
encoded data. To find character corresponding to current bits, we use following simple steps.
The below code takes a string as input, it encodes it and save in a variable encodedString.
Then it decodes it and print the original string.
The below code performs full Huffman Encoding and Decoding of a given input data.
278
Chapter 39. Huffman Decoding
279
Chapter 39. Huffman Decoding
top->right = right;
minHeap.push(top);
}
storeCodes(minHeap.top(), "");
}
280
Chapter 39. Huffman Decoding
Output:
Input: "geeksforgeeks"
Total number of character i.e. input length: 13
Size: 13 character occurrences * 8 bits = 104 bits or 13 bytes.
Input: "geeksforgeeks"
281
Chapter 39. Huffman Decoding
------------------------------------------------
Character | Frequency | Binary Huffman Value |
------------------------------------------------
e | 4 | 10 |
f | 1 | 1100 |
g | 2 | 011 |
k | 2 | 00 |
o | 1 | 010 |
r | 1 | 1101 |
s | 2 | 111 |
------------------------------------------------
Hence, we could see that after encoding the data we have saved a large amount of data.
The above method can also help us to determine the value of N i.e. the length of the encoded
data.
Source
https://www.geeksforgeeks.org/huffman-decoding/
282
Chapter 40
We first sort the jobs according to their starting time. Then we start two jobs simultaneously
and check if the starting time of third job and so on is greater than the ending time of and
of the previous two jobs.
The C++ implementation the above idea is given below.
283
Chapter 40. Job Scheduling with two jobs allowed at a time
else
return false;
}
return true;
}
// Driver code
int main()
{
int startin[] = { 1, 2, 4 }; // starting time of jobs
int endin[] = { 2, 3, 5 }; // ending times of jobs
int n = sizeof(startin) / sizeof(startin[0]);
cout << checkJobs(startin, endin, n);
284
Chapter 40. Job Scheduling with two jobs allowed at a time
return 0;
}
Output:
An alternate solution is to find maximum number of jobs that needs to be scheduled at any
time. If this count is more than 2, return false. Else return true.
Source
https://www.geeksforgeeks.org/job-scheduling-two-jobs-allowed-time/
285
Chapter 41
Solution: In the optimum sequence of jobs, the total volume of goods left at the end of all
jobs is 222.503
Example-2:
Solution: In the optimum sequence of jobs the total volume of goods left at the end of all
jobs is 145.72
286
Chapter 41. Job Selection Problem – Loss Minimization Strategy Set 2
Explanation –
Since this is an optimization problem, we can try to solve this problem by using a greedy
algorithm. On each day we make a selection from among the goods that are yet to be
produced. Thus all we need is a local selection criteria or heuristic, which when applied to
select the jobs will give us the optimum result.
Instead of trying to maximize the volume, we can also try to minimize the losses. Since the
total volume that can be obtained from all goods is also constant, if we minimize the losses
we are guaranteed to get the optimum answer.
Now consider any good having volume V
Loss after Day 1: PV
Loss after Day 2: PV + P(1-P)V or V(2P-P^2)
Loss after Day 3: V(2P-P^2) + P(1 – 2P + P^2)V or V(3P – 3P^2 + P^3)
As the day increases the losses too increase. So the trick would be to ensure that the goods
are not kept idle after production. Further, since we are required to produce at least one
job per day, we should perform low volume jobs, and then perform the high volume jobs.
This strategy works due to two factors.
So in order to obtain the optimum solution we produce the larger volume goods later on.
For the first day select the good with least volume and produce it. Remove the produced
good from the list of goods. For the next day repeat the same. Keep repeating while there
are goods left to be produced.
When calculating the total volume at the end of production, keep in mind the the
good produced on day i, will have times its volume left. Ev-
idently, the good produced on day N (last day) will have its volume intact since
.
Algorithm –
Complexity –
We perform exactly N push() and pop() operations each of which takes log (N) time. Hence
time complexity is O( N * log(N) ).
287
Chapter 41. Job Selection Problem – Loss Minimization Strategy Set 2
#include <bits/stdc++.h>
using namespace std;
// Print result
cout << endl << result << endl;
}
// Driver code
int main()
{
// For implementation simplicity days are numbered
// from 1 to N. Hence 1 based indexing is used
vector<int> V{ -1, 3, 5, 4, 1, 2, 7, 6, 8, 9, 10 };
288
Chapter 41. Job Selection Problem – Loss Minimization Strategy Set 2
double P = 0.10;
optimum_sequence_jobs(V, P);
return 0;
}
Output –
1 2 3 4 5 6 7 8 9 10
41.3811
Source
https://www.geeksforgeeks.org/job-selection-problem-loss-minimization-strategy-set-2/
289
Chapter 42
290
Chapter 42. Job Sequencing Problem Set 1 (Greedy Algorithm)
A Simple Solution is to generate all subsets of given set of jobs and check individual subset
for feasibility of jobs in that subset. Keep track of maximum profit among all feasible subsets.
The time complexity of this solution is exponential.
This is a standard Greedy Algorithmproblem. Following is algorithm.
// Program to find the maximum profit job sequence from a given array
// of jobs with deadlines and profits
#include<iostream>
#include<algorithm>
using namespace std;
291
Chapter 42. Job Sequencing Problem Set 1 (Greedy Algorithm)
Output:
Time Complexity of the above solution is O(n2 ). It can be optimized using Disjoint Set
Data Structure. Please refer below post for details.
Job Sequencing Problem Set 2 (Using Disjoint Set)
Sources:
http://ocw.mit.edu/courses/civil-and-environmental-engineering/1-204-computer-algorithms-in-systems-engineering
lecture-notes/MIT1_204S10_lec10.pdf
292
Chapter 42. Job Sequencing Problem Set 1 (Greedy Algorithm)
This article is contributed by Shubham. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/job-sequencing-problem-set-1-greedy-algorithm/
293
Chapter 43
A greedy solution of time complexity O(n2 ) is already discussed here. Below is the simple
Greedy Algorithm.
294
Chapter 43. Job Sequencing Problem Set 2 (Using Disjoint Set)
• If the current job can fit in the current result sequence without missing the
deadline, add current job to the result. Else ignore the current job.
The costly operation in the Greedy solution is to assign a free slot for a job. We were travers-
ing each and every slot for a job and assigning the greatest possible time slot(<deadline)
which was available.
What does greatest time slot means?
Suppose that a job J1 has a deadline of time t = 5. We assign the greatest time slot which
is free and less than the deadline i.e 4-5 for this job. Now another job J2 with deadline of 5
comes in, so the time slot allotted will be 3-4 since 4-5 has already been allotted to job J1.
Why to assign greatest time slot(free) to a job?
Now we assign the greatest possible time slot since if we assign a time slot even lesser than
the available one than there might be some other job which will miss its deadline.
Example:
J1 with deadline d1 = 5, profit 40
J2 with deadline d2 = 1, profit 20
Suppose that for job J1 we assigned time slot of 0-1. Now job J2 cannot be performed since
we will perform Job J1 during that time slot.
Using Disjoint Set for Job Sequencing
All time slots are individual sets initially. We first find the maximum deadline of all jobs.
Let the max deadline be m. We create m+1 individual sets. If a job is assigned a time slot
of t where t => 0, then the job is scheduled during [t-1, t]. So a set with value X represents
the time slot [X-1, X].
We need to keep track of the greatest time slot available which can be allotted to a given job
having deadline. We use the parent array of Disjoint Set Data structures for this purpose.
The root of the tree is always the latest available slot. If for a deadline d, there is no slot
available, then root would be 0. Below are detailed steps.
Initialize Disjoint Set: Creates initial disjoint sets.
295
Chapter 43. Job Sequencing Problem Set 2 (Using Disjoint Set)
Union :
296
Chapter 43. Job Sequencing Problem Set 2 (Using Disjoint Set)
struct DisjointSet
{
int *parent;
// Constructor
DisjointSet(int n)
{
parent = new int[n+1];
// Path Compression
int find(int s)
{
/* Make the parent of the nodes in the path
from u--> parent[u] point to parent[u] */
if (s == parent[s])
return s;
return parent[s] = find(parent[s]);
}
// Makes u as parent of v.
void merge(int u, int v)
{
//update the greatest available
//free slot to u
parent[v] = u;
}
};
297
Chapter 43. Job Sequencing Problem Set 2 (Using Disjoint Set)
298
Chapter 43. Job Sequencing Problem Set 2 (Using Disjoint Set)
Java
// Constructor
DisjointSet(int n)
{
parent = new int[n + 1];
// Path Compression
int find(int s)
{
/* Make the parent of the nodes in the path
from u--> parent[u] point to parent[u] */
if (s == parent[s])
return s;
return parent[s] = find(parent[s]);
}
// Makes u as parent of v.
void merge(int u, int v)
{
//update the greatest available
//free slot to u
parent[v] = u;
}
}
299
Chapter 43. Job Sequencing Problem Set 2 (Using Disjoint Set)
{
// Each job has a unique-id, profit and deadline
char id;
int deadline, profit;
// Constructors
public Job() { }
public Job(char id,int deadline,int profit)
{
this.id = id;
this.deadline = deadline;
this.profit = profit;
}
300
Chapter 43. Job Sequencing Problem Set 2 (Using Disjoint Set)
// Driver code
class Main
{
public static void main(String args[])
{
ArrayList<Job> arr=new ArrayList<Job>();
arr.add(new Job('a',2,100));
arr.add(new Job('b',1,19));
arr.add(new Job('c',2,27));
arr.add(new Job('d',1,25));
arr.add(new Job('e',3,15));
System.out.println("Following jobs need to be "+
"executed for maximum profit");
Job.printJobScheduling(arr);
}
}
Output:
Source
https://www.geeksforgeeks.org/job-sequencing-using-disjoint-set-union/
301
Chapter 44
Input : L = {1, 2, 3, 5, 6}
T = {2, 4, 1, 3, 2}
Output : 3, 5, 4, 1, 2
Explanation: We should complete jobs
3, 5, 4, 1 and then 2 in this order.
Let us consider two extreme cases and we shall deduce the general case solution from them.
All jobs take same time to finish, i.e Ti = k for all i. Since all jobs take same time to finish
we should first select jobs which have large Loss (Li). We should select jobs which have the
302
Chapter 44. Job Sequencing Problem – Loss Minimization
Source
https://www.geeksforgeeks.org/job-sequencing-problem-loss-minimization/
303
Chapter 45
There is no polynomial time solution available for this problem as the problem is a known
NP-Hard problem. There is a polynomial time Greedy approximate algorithm, the greedy
algorithm provides a solution which is never worse that twice the optimal solution. The
greedy solution works only if the distances between cities follow Triangular Inequality (Dis-
tance between two points is always smaller than sum of distances through a third point).
304
Chapter 45. K Centers Problem Set 1 (Greedy Approximate Algorithm)
305
Chapter 45. K Centers Problem Set 1 (Greedy Approximate Algorithm)
Source:
http://algo2.iti.kit.edu/vanstee/courses/kcenter.pdf
This article is contributed by Harshit. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/k-centers-problem-set-1-greedy-approximate-algorithm/
306
Chapter 46
We have discussed one implementation of Kruskal’s algorithm in previous post. In this post,
a simpler implementation for adjacency matrix is discussed.
#define V 5
int parent[V];
307
Chapter 46. Kruskal’s Algorithm (Simple Implementation for Adjacency Matrix)
union1(a, b);
printf("Edge %d:(%d, %d) cost:%d \n",
edge_count++, a, b, min);
mincost += min;
}
printf("\n Minimum cost= %d \n", mincost);
}
308
Chapter 46. Kruskal’s Algorithm (Simple Implementation for Adjacency Matrix)
(0)--(1)--(2)
| / \ |
6| 8/ \5 |7
| / \ |
(3)-------(4)
9 */
int cost[][V] = {
{ INT_MAX, 2, INT_MAX, 6, INT_MAX },
{ 2, INT_MAX, 3, 8, 5 },
{ INT_MAX, 3, INT_MAX, INT_MAX, 7 },
{ 6, 8, INT_MAX, INT_MAX, 9 },
{ INT_MAX, 5, 7, 9, INT_MAX },
};
return 0;
}
Output:
Minimum cost= 16
Note that the above solution is not efficient. The idea is to provide a simple implementation
for adjacency matrix representations. Please see below for efficient implementations.
Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
Kruskal’s Minimum Spanning Tree using STL in C++
Source
https://www.geeksforgeeks.org/kruskals-algorithm-simple-implementation-for-adjacency-matrix/
309
Chapter 47
The step#2 uses Union-Find algorithm to detect cycle. So we recommend to read following
post as a prerequisite.
Union-Find Algorithm Set 1 (Detect Cycle in a Graph)
Union-Find Algorithm Set 2 (Union By Rank and Path Compression)
The algorithm is a Greedy Algorithm. The Greedy Choice is to pick the smallest weight
edge that does not cause a cycle in the MST constructed so far. Let us understand it with
an example: Consider the below input graph.
310
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
The graph contains 9 vertices and 14 edges. So, the minimum spanning tree formed will be
having (9 – 1) = 8 edges.
After sorting:
Weight Src Dest
1 7 6
2 8 2
2 6 5
4 0 1
4 2 5
6 8 6
7 2 3
7 7 8
8 0 7
8 1 2
9 3 4
10 5 4
11 1 7
14 3 5
Now pick all edges one by one from sorted list of edges
1. Pick edge 7-6: No cycle is formed, include it.
311
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
6. Pick edge 8-6: Since including this edge results in cycle, discard it.
7. Pick edge 2-3: No cycle is formed, include it.
8. Pick edge 7-8: Since including this edge results in cycle, discard it.
9. Pick edge 0-7: No cycle is formed, include it.
312
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
10. Pick edge 1-2: Since including this edge results in cycle, discard it.
11. Pick edge 3-4: No cycle is formed, include it.
Since the number of edges included equals (V – 1), the algorithm stops here.
C/C++
313
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
return graph;
}
return subsets[i].parent;
}
314
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
315
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
result[e++] = next_edge;
Union(subsets, x, y);
}
// Else discard the next_edge
}
316
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
graph->edge[3].dest = 3;
graph->edge[3].weight = 15;
KruskalMST(graph);
return 0;
}
Java
class Graph
{
// A class to represent a graph edge
class Edge implements Comparable<Edge>
{
int src, dest, weight;
317
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
{
V = v;
E = e;
edge = new Edge[E];
for (int i=0; i<e; ++i)
edge[i] = new Edge();
}
return subsets[i].parent;
}
318
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
319
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
// Driver Program
public static void main (String[] args)
{
graph.KruskalMST();
}
320
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
}
//This code is contributed by Aakash Hasija
Python
def __init__(self,vertices):
self.V= vertices #No. of vertices
self.graph = [] # default dictionary
# to store graph
321
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
rank[xroot] += 1
parent = [] ; rank = []
322
Chapter 47. Kruskal’s Minimum Spanning Tree Algorithm Greedy Algo-2
# Driver code
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
g.KruskalMST()
Time Complexity: O(ElogE) or O(ElogV). Sorting of edges takes O(ELogE) time. After
sorting, we iterate through all edges and apply find-union algorithm. The find and union
operations can take atmost O(LogV) time. So overall complexity is O(ELogE + ELogV)
time. The value of E can be atmost O(V2 ), so O(LogV) are O(LogE) same. Therefore,
overall time complexity is O(ElogE) or O(ElogV)
References:
http://www.ics.uci.edu/~eppstein/161/960206.html
http://en.wikipedia.org/wiki/Minimum_spanning_tree
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please
write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.
Source
https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/
323
Chapter 48
Simple Approach:
A simple solution is, we can use naive approach.We will check absolute difference of every
pair in the array and we will find the maximum value of it.So we will run two loops one is
for i and one is for j complexity of this method is O(N^2)
C
324
Chapter 48. Largest gap in an array
int main()
{
int arr[] = { -1, 2, 3, -4, -10, 22 };
int size = sizeof(arr) / sizeof(arr[0]);
printf("Largest gap is : %d", solve(arr, size));
return 0;
}
Java
class GFG
{
// function to solve
// the given problem
static int solve(int []a,
int n)
{
int max1 = Integer.MIN_VALUE ;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] -
a[j]) > max1)
{
max1 = Math.abs(a[i] -
a[j]);
}
325
Chapter 48. Largest gap in an array
}
}
return max1;
}
// Driver Code
static public void main (String[] args)
{
int []arr = {-1, 2, 3,
-4, -10, 22};
int size = arr.length;
System.out.println("Largest gap is : " +
solve(arr, size));
}
}
C#
// A C# program to find
// largest gap between
// two elements in an array.
using System;
class GFG
{
// function to solve
// the given problem
static int solve(int []a,
int n)
{
int max1 = int.MinValue ;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.Abs(a[i] -
a[j]) > max1)
{
max1 = Math.Abs(a[i] -
a[j]);
}
}
}
return max1;
326
Chapter 48. Largest gap in an array
// Driver Code
static public void Main ()
{
int []arr = {-1, 2, 3,
-4, -10, 22};
int size = arr.Length;
Console.WriteLine("Largest gap is : " +
solve(arr, size));
}
}
PHP
<?php
// A PHP program to find
// largest gap between
// two elements in an array.
// function to solve
// the given problem
function solve($a, $n)
{
$max1 = PHP_INT_MIN;
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
{
if (abs($a[$i] -
$a[$j]) > $max1)
{
$max1 = abs($a[$i] -
$a[$j]);
}
}
}
return $max1;
}
// Driver Code
$arr = array(-1, 2, 3,
-4, -10, 22);
$size = count($arr);
echo "Largest gap is : ",
327
Chapter 48. Largest gap in an array
solve($arr, $size);
Output:
Largest gap is : 32
Better Approach:
Now we will see a better approach it is greedy approach which can solve this problem in
O(N). we will find maximum and minimum element of the array which can be done in O(N)
and then we will return value of (maximum-minimum).
C
int main()
{
int arr[] = { -1, 2, 3, 4, -10 };
int size = sizeof(arr) / sizeof(arr[0]);
printf("Largest gap is : %d", solve(arr, size));
return 0;
}
328
Chapter 48. Largest gap in an array
Java
class GFG {
// Driver code
public static void main (String[] args)
{
int []arr = { -1, 2, 3, 4, -10 };
int size = arr.length;
System.out.println("Largest gap is : "
+ solve(arr, size));
}
}
C#
// A C# program to find
// largest gap between
// two elements in an array.
using System;
329
Chapter 48. Largest gap in an array
class GFG
{
// function to solve
// the given problem
static int solve(int []a,
int n)
{
int min1 = a[0];
int max1 = a[0];
return Math.Abs(min1 -
max1);
}
// Driver code
public static void Main ()
{
int []arr = {-1, 2, 3, 4, -10};
int size = arr.Length;
Console.WriteLine("Largest gap is : " +
solve(arr, size));
}
}
PHP
<?php
// A PHP program to find
// largest gap between
// two elements in an array.
// function to solve
// the given problem
function solve($a, $n)
330
Chapter 48. Largest gap in an array
{
$min1 = $a[0];
$max1 = $a[0];
// Driver Code
$arr = array(-1, 2, 3, 4, -10);
$size = count($arr);
echo "Largest gap is : ",
solve($arr, $size);
Output:
Largest gap is : 14
Improved By : vt_m
Source
https://www.geeksforgeeks.org/largest-gap-in-an-array/
331
Chapter 49
Brute Force Approach : Generate all permutation of the array and then pick the one
which satisfies the condition of at most K swaps. The time complexity of this approach is
O(n!).
Optimized Approach : In this greedy approach, first find the largest element present
in the array which is greater than(if the 1st position element is not the greatest) the 1st
position and which can be placed at the 1st position with at-most K swaps. After finding
that element, note its index. Then, swap elements of the array and update K value. Apply
this procedure for other positions till k is non-zero or array becomes lexicographically largest.
Below is the implementation of above approach :
332
Chapter 49. Largest lexicographic array with at-most K consecutive swaps
C++
// Driver code
int main()
{
int arr[] = { 3, 5, 4, 1, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
KSwapMaximum(arr, n, k);
333
Chapter 49. Largest lexicographic array with at-most K consecutive swaps
Java
class GFG
{
static void SwapInts(int array[],
int position1,
int position2)
{
// Swaps elements
// in an array.
// Assign to the
// second element
array[position1] = array[position2];
// Assign to the
// first element
array[position2] = temp;
}
// Function which
// modifies the array
static void KSwapMaximum(int []arr,
int n, int k)
{
for (int i = 0;
i < n - 1 && k > 0; ++i)
{
// Here, indexPositionition
// is set where we want to
// put the current largest
334
Chapter 49. Largest lexicographic array with at-most K consecutive swaps
// integer
int indexPosition = i;
for (int j = i + 1; j < n; ++j)
{
// If we exceed the
// Max swaps then
// break the loop
if (k <= j - i)
break;
// Driver code
public static void main(String args[])
{
int []arr = { 3, 5, 4, 1, 2 };
int n = arr.length;
int k = 3;
KSwapMaximum(arr, n, k);
335
Chapter 49. Largest lexicographic array with at-most K consecutive swaps
// Manish Shaw(manishshaw1)
Python3
arr = [3, 5, 4, 1, 2]
# Function which
# modifies the array
def KSwapMaximum(n, k) :
global arr
for i in range(0, n - 1) :
if (k > 0) :
# Here, indexPositionition
# is set where we want to
# put the current largest
# integer
indexPosition = i
for j in range(i + 1, n) :
336
Chapter 49. Largest lexicographic array with at-most K consecutive swaps
# indexPosition-i elements
k = k - indexPosition - i
# Driver code
n = len(arr)
k = 3
KSwapMaximum(n, k)
C#
// C# program to find
// lexicographically
// maximum value after
// k swaps.
using System;
class GFG
{
static void SwapInts(int[] array,
int position1,
int position2)
{
// Swaps elements in an array.
// Function which
// modifies the array
static void KSwapMaximum(int []arr,
int n, int k)
337
Chapter 49. Largest lexicographic array with at-most K consecutive swaps
{
for (int i = 0;
i < n - 1 && k > 0; ++i)
{
// Here, indexPositionition
// is set where we want to
// put the current largest
// integer
int indexPosition = i;
for (int j = i + 1; j < n; ++j)
{
// If we exceed the
// Max swaps then
// break the loop
if (k <= j - i)
break;
// Driver code
static void Main()
{
int []arr = new int[]{ 3, 5, 4, 1, 2 };
int n = arr.Length;
int k = 3;
KSwapMaximum(arr, n, k);
338
Chapter 49. Largest lexicographic array with at-most K consecutive swaps
PHP
<?php
// PHP program to find
// lexicographically
// maximum value after
// k swaps.
// Function which
// modifies the array
function KSwapMaximum(&$arr, $n, $k)
{
for ($i = 0;
$i < $n - 1 &&
$k > 0; $i++)
{
// Here, indexPositionition
// is set where we want to
// put the current largest
// integer
$indexPosition = $i;
for ($j = $i + 1;
$j < $n; $j++)
{
339
Chapter 49. Largest lexicographic array with at-most K consecutive swaps
// arr[indexPosition]
if ($arr[$j] > $arr[$indexPosition])
$indexPosition = $j;
}
// Driver code
$arr = array( 3, 5, 4, 1, 2 );
$n = count($arr);
$k = 3;
Output:
5 4 3 1 2
Source
https://www.geeksforgeeks.org/largest-lexicographic-array-with-at-most-k-consecutive-swaps/
340
Chapter 50
Input : 313551
Output : 531135
Explanations : 531135 is the largest number
which is a palindrome, 135531, 315513 and other
numbers can also be formed but we need the highest
of all of the palindromes.
Input : 331
Output : 313
Input : 3444
Output : Pallindrome cannot be formed
Naive Approach : The naive approach will be to try all the permutations possible, and
print the largest of such combinations which is a palindrome.
Efficient Approach : An efficient approach will be to use Greedy algorithm. Since the
number is large, store the number in a string. Store the count of occurrences of every digit
in the given number in a map. Check if it is possible to form a palindrome or not. If the
digits of the given number can be rearranged to form a palindrome, then apply the greedy
approach to obtain the number. Check for the occurrence of every digit (9 to 0), and place
341
Chapter 50. Largest palindromic number by permuting digits
every available digit at front and back. Initially, the front pointer will be at index 0,
as the largest digit will be placed at first to make the number a large one. With
every step, move the front pointer 1 position ahead. If the digit occurs an odd number of
times, then place one digit in the middle and rest of the even number of digits at
front and back. Keep repeating the process (map[digit]/2) number of times for a single
digit. After placing a particular digit which occurs an even number of times at the front
and back, move the front pointer one step ahead. The placing is done till map[digit] is 0.
The char array will have the largest palindromic number possible after completion of the
placing of digits greedily.
In the worst case, the time complexity will be O(10 * (length of string/2)), in case the
number consists of a same digit at every position.
Below is the implementation of the above idea :
// if occurrence is odd
if (m[s[i] - '0'] & 1)
countodd++;
// if number exceeds 1
if (countodd > 1)
return false;
}
return true;
}
// string length
int l = s.length();
342
Chapter 50. Largest palindromic number by permuting digits
// pointer of front
int front = 0;
343
Chapter 50. Largest palindromic number by permuting digits
// Driver Code
int main()
{
string s = "313551";
largestPalindrome(s);
return 0;
}
Output:
531135
Source
https://www.geeksforgeeks.org/largest-palindromic-number-permuting-digits/
344
Chapter 51
345
Chapter 51. Largest permutation after at most k swaps
// Driver code
int main()
{
int arr[] = {4, 5, 2, 1, 3};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
KswapPermutation(arr, n, k);
cout << "Largest permutation after "
346
Chapter 51. Largest permutation after at most k swaps
Java
347
Chapter 51. Largest permutation after at most k swaps
// Driver method
public static void main(String[] args)
{
KswapPermutation(arr, n, k);
Python
for i in range(n):
348
Chapter 51. Largest permutation after at most k swaps
pos[n-i] = i
# Driver code
arr = [4, 5, 2, 1, 3]
n = len(arr)
k = 3
KswapPermutation(arr, N, K)
C#
class GFG {
349
Chapter 51. Largest permutation after at most k swaps
// Driver method
public static void Main()
{
KswapPermutation(arr, n, k);
Output:
Largest permutation after 3 swaps:
5 4 3 2 1
350
Chapter 51. Largest permutation after at most k swaps
Source
https://www.geeksforgeeks.org/largest-permutation-k-swaps/
351
Chapter 52
Length and Breadth of rectangle such that ratio of Area to diagonal^2 is maximum - Geeks-
forGeeks
Given an array of positive integers. The task is to choose a pair of elements from the given
array such that they represent the length and breadth of a rectangle and the ratio of its
area and its diagonal2 is maximum.
Note: The array must contains all sides of the rectangle. That is you can choose elements
from array which appears atleast twice as a rectangle has two sides of same length and two
sides of same breadth.
Examples:
Given below are some properties of the rectangle that are to be satisfied in order to form it.
• A rectangle can only be formed when we have at least pair of equal integers. An
integer occurring once can’t be a part of any rectangle. So, in our solution, we will
consider only the integers whose occurrence is more than once.
352
Chapter 52. Length and Breadth of rectangle such that ratio of Area to diagonal^2 is
maximum
• The ratio of Area and its diameter 2 is lb/(l2 + b2 ) is a monotonic decreasing function
in term of one variable. This means if we are fixing the length then as we will decrease
the breadth the ratio got decreases and accordingly same for fixed breadth. Taking
advantage of this we need not iterate the whole array for finding the length for a fixed
breadth.
Algorithm :
353
Chapter 52. Length and Breadth of rectangle such that ratio of Area to diagonal^2 is
maximum
length = arr_pairs[i];
breadth = arr_pairs[i - 1];
}
}
// Driver Code
int main()
{
int arr[] = { 4, 2, 2, 2, 5, 6, 5, 6, 7, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
findLandB(arr, n);
return 0;
}
Output:
2, 2
Source
https://www.geeksforgeeks.org/length-and-breadth-of-rectangle-such-that-ratio-of-area-to-diagonal2-is-maximum/
354
Chapter 53
Lexicographically largest
subsequence such that every
character occurs at least k times
Lexicographically largest subsequence such that every character occurs at least k times -
GeeksforGeeks
Given a string S and an integer K. The task is to find lexicographically largest subsequence
of S, say T, such that every character in T must occur at least K times.
Examples:
Input : S = "banana", K = 2.
Output : nn
Possible subsequence where each character exists at least 2 times are:
The idea is to solve greedily the above problem. If we want to make the subsequence
lexicographically largest, we must give priority to lexicographically larger characters. ‘z’ is
the largest character, let suppose z occurs fz times in S. If fz >= K, append ‘z’z k times in
the string T and keep removing characters from the left of S until all the z’s are removed.
Apply the strategy with ‘y’, ‘w’, ….., ‘a’. In the end you will find the answer.
Let see an example. Suppose S = “zzwzawa” and K = 2. Start with the largest character
‘z’. Here fz = 3 >= K. So T will become “zzz” and we will remove letters from the left of
S until all the z’s are removed. So now S will became “awa”. Next largest is ‘y’ but that
occurs 0 times in k so we will skip it. We will skip ‘w’, ‘v’ etc also until we go to ‘a’ which
occurs 2 times. Now T will become “zzzaa” and S will become a empty string. Our answer
is “zzzaa”.
Below is C++ implementation of this approach:
355
Chapter 53. Lexicographically largest subsequence such that every character occurs at least
k times
// Driver code
int main()
{
356
Chapter 53. Lexicographically largest subsequence such that every character occurs at least
k times
Output:
nn
Source
https://www.geeksforgeeks.org/lexicographically-largest-subsequence-every-character-occurs-least-k-times/
357
Chapter 54
We strongly recommend that you click here and practice it, before moving on to the solution.
Naive approach is to generate all the permutation of array and pick the smallest one
which satisfy the condition of at-most k swaps. Time complexity of this approach is Ω(n!),
which will definitely time out for large value of n.
An Efficient approach is to think greedily. We first pick the smallest element from array a1 ,
a2 , a3 …(ak or an ) [We consider ak when k is smaller, else n]. We place the smallest element
358
Chapter 54. Lexicographically smallest array after at-most K consecutive swaps
to the a0 position after shifting all these elements by 1 position right. We subtract number
of swaps (number of swaps is number of shifts minus 1) from k. If still we are left with k
> 0 then we apply the same procedure from the very next starting position i.e., a2 , a3 ,…(ak
or an ) and then place it to the a1 position. So we keep applying the same process until k
becomes 0.
C++
// Driver code
int main()
{
359
Chapter 54. Lexicographically smallest array after at-most K consecutive swaps
minimizeWithKSwaps(arr, n, k);
Java
360
Chapter 54. Lexicographically smallest array after at-most K consecutive swaps
arr[j]=arr[j-1];
arr[j-1]=temp;
}
// Driver method
public static void main(String[] args)
{
minimizeWithKSwaps(arr, n, k);
Python
for i in range(n-1):
361
Chapter 54. Lexicographically smallest array after at-most K consecutive swaps
# Driver Code
n, k = 5, 3
arr = [7, 6, 9, 2, 1]
minimizeWithKSwaps(arr, n, k)
C#
class GFG {
362
Chapter 54. Lexicographically smallest array after at-most K consecutive swaps
// i + 1 to max k or n
if (arr[j] < arr[pos])
pos = j;
}
// Driver method
public static void Main()
{
int []arr = {7, 6, 9, 2, 1};
int n = arr.Length;
int k = 3;
// Function calling
minimizeWithKSwaps(arr, n, k);
php
<?php
// php program to find lexicographically minimum
// value after k swaps.
363
Chapter 54. Lexicographically smallest array after at-most K consecutive swaps
// Driver code
$arr = array(7, 6, 9, 2, 1);
$n = count($arr);
$k = 3;
364
Chapter 54. Lexicographically smallest array after at-most K consecutive swaps
?>
Output: 2 7 6 9 1
Source
https://www.geeksforgeeks.org/lexicographically-smallest-array-k-consecutive-swaps/
365
Chapter 55
Lexicographically smallest
permutation of a string with
given subsequences
Given a string consisting only of two lowercase characters and and two numbers
and . The task is to print the lexicographically smallest permutation of the given string
such that the count of subsequences of is and of is . If no such string exists,
print “Impossible” (without quotes).
Examples:
Approach: First of all, by induction it can prove that the product of count of ‘x’ and count
of ‘y’ should be equal to the sum of the count of a subsequence of ‘xy’ and ‘yx’ for any given
string. If this does not hold then the answer is ‘Impossible’ else answer always exist.
Now, sort the given string so the count of a subsequence of ‘yx’ becomes zero. Let nx be
the count of ‘x’ and ny be count of ‘y’. let a and b be the count of subsequence ‘xy’ and ‘yx’
respectively, then a = nx*ny and b = 0. Then, from beginning of the string find the ‘x’
which has next ‘y’ to it and swap both untill you reach end of the string. In each swap a is
decremented by 1 and b is incremented by 1. Repeat this until the count of a subsequence
of ‘yx’ is achieved i:e a becomes p and b becomes q.
366
Chapter 55. Lexicographically smallest permutation of a string with given subsequences
Source
https://www.geeksforgeeks.org/lexicographically-smallest-permutation-of-a-string-with-given-subsequences/
C++
sort(s.begin(), s.end());
int a = nx * ny, b = 0, i, j;
367
Chapter 55. Lexicographically smallest permutation of a string with given subsequences
if (a == p && b == q) {
return s;
}
// Driver code
int main()
{
string s = "yxxyx";
int p = 3, q = 3;
return 0;
}
Java
// Java program to find lexicographically
// smallest string such that count of
// subsequence ‘xy’ and ‘yx’ is p and
// q respectively.
import java.util.*;
class GFG
{
368
Chapter 55. Lexicographically smallest permutation of a string with given subsequences
static int nx = 0, ny = 0;
static boolean check(String s,
int p, int q)
{
// count total ‘x’ and ‘y’ in string
for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == ’x’) nx++; else ny++; } // condition
to check // existence of answer if ((nx * ny) != (p + q)) return true; else return false; }
public static String smallestPermutation(String s, int p, int q) { if (check(s, p, q) == true) {
return ”Impossible”; } char tempArray[] = s.toCharArray(); Arrays.sort(tempArray); String
str = new String(tempArray); int a = nx * ny, b = 0, i = 0, j = 0; if (a == p && b == q)
{ return str; } while (1 > 0)
{
// Find index of ‘x’ to swap with ‘y’.
for (i = 0; i < str.length() - 1; ++i) { if (str.charAt(i) == ’x’ && str.charAt(i + 1) == ’y’)
break; } for (j = i; j < str.length() - 1; j++) { if (str.charAt(j) == ’x’ && str.charAt(j +
1) == ’y’) { StringBuilder sb = new StringBuilder(str); sb.setCharAt(j, str.charAt(j + 1));
sb.setCharAt(j + 1, str.charAt(j)); str = sb.toString(); /* char ch[] = str.toCharArray();
char temp = ch[j+1]; ch[j+1] = ch[j]; ch[j] = temp;*/ a--; // ’xy’ decrement by 1 b++; // ’yx’
increment by 1 // check if count of ’xy’ and // ’yx’ becomes equal to p // and q respectively.
if (a == p && b == q) { return str; } } } } } // Driver Code public static void main (String[]
args) { String s = ”yxxyx”; int p = 3, q = 3; System.out.print(smallestPermutation(s, p,
q)); } } // This code is contributed by Kirti_Mangal [tabbyending]
Output:
xyxyx
369
Chapter 56
A Naive Approach is to generate all subsequences using power-set and check for the
longest subsequence whose average is less than K.
Time Complexity: O(2N * N )
An efficient approach is to sort the array elements and find the average of elements starting
from the left. Insert the average of elements computed from the left into the container(vector
or arrays). Sort the container’s element and then use binary search to search for the number
K in the container. The length of the longest subsequence will thus be the index number
which upper_bound() returns for every query.
Below is the implementation of the above approach.
370
Chapter 56. Longest subsequence whose average is less than K
// number of queries
// Driver Code
int main()
{
int a[] = { 1, 3, 2, 5, 4 };
int n = sizeof(a) / sizeof(a[0]);
// 4 queries
int q[] = { 4, 2, 1, 5 };
int m = sizeof(q) / sizeof(q[0]);
371
Chapter 56. Longest subsequence whose average is less than K
longestSubsequence(a, n, q, m);
return 0;
}
Output:
Answer to Query1: 5
Answer to Query2: 2
Answer to Query3: 0
Answer to Query4: 5
Source
https://www.geeksforgeeks.org/longest-subsequence-whose-average-is-less-than-k/
372
Chapter 57
Input : N = 3, M = 4
Output : 8
Explanation:
array is 4 0 0
In 4 steps element at index 1 is increased, so the array becomes {4, 4, 0}. In
the next 4 steps the element at index 3 is increased so array becomes {4, 4, 4}
Thus, 4 + 4 = 8 operations are required to make all the array elements equal
Input : N = 4, M = 4
Output : 9
Explanation:
The steps are shown in the flowchart given below
Refer to the flowchart given below.
373
Chapter 57. Make array elements equal in Minimum Steps
374
Chapter 57. Make array elements equal in Minimum Steps
Approach:
To maximise the Number of Increments per Step, more number of Unbalances are created
(array[i]>array[i+1]),
Step 1, element 0 >element 1 so element 1 is incremented,
Step 2, element 1> element 2 so element 2 is incremented by 1
Step 3, element 0 > element 1 and element 2> element 3 so element 1 &3 are incremented
by 1
Step 4, element 1 > element 2 element 3 > element 4 so element 2 & 4 are incremented
Step 5, element 0> element 1; element 2>element 3 ;element 4> element 5; so element 1, 3,
&5 are incremented.
and so on…
Consider the following array,
500000
1) 5 1 0 0 0 0
2) 5 1 1 0 0 0
3) 5 2 1 1 0 0
4) 5 2 2 1 1 0
5) 5 3 2 2 1 1
6) 5 3 3 2 2 1
7) 5 4 3 3 2 2
8) 5 4 4 3 3 2
9) 5 5 4 4 3 3
10) 5 5 5 4 4 3
11) 5 5 5 5 4 4
12) 5 5 5 5 5 4
13) 5 5 5 5 5 5
Notice that after an unbalance is created (i.e array[i]>array[i+1]) the element gets incre-
mented by one in alternate steps. In step 1 element 1 gets incremented to 1, in step 2
element 2 gets incremented to 1, in step 3 element 3 gets incremented to 1, so in step n-1,
n-1th element will become 1. After that n-1th element is increased by 1 on alternate steps
until it reaches the value at element 0. Then the entire array becomes equal.
So the pattern followed by the last element is
(0, 0, 0.., 0) till (N – 4)th element becomes 1 which is n-4 steps
and after that,
(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, … M – 1, M – 1, M) which is 2*m + 1 steps.
So the Final Result becomes (N – 3) + 2 * M
There are a few corner cases which need to be handled, viz. When N = 1, array has only
a single element, so the number of steps required = 0. and When N = 2, number of steps
required equal to M
C++
375
Chapter 57. Make array elements equal in Minimum Steps
#include <bits/stdc++.h>
using namespace std;
return 2 * M + (N - 3);
}
// Driver Code
int main()
{
int N = 4, M = 4;
cout << steps(N, M);
return 0;
}
Java
import java.io.*;
class GFG {
376
Chapter 57. Make array elements equal in Minimum Steps
return 2 * M + (N - 3);
}
// Driver Code
public static void main (String[] args)
{
int N = 4, M = 4;
System.out.print( steps(N, M));
}
}
Python3
return 2 * M + (N - 3)
# Driver Code
N = 4
M = 4
print(steps(N,M))
C#
377
Chapter 57. Make array elements equal in Minimum Steps
class GFG
{
return 2 * M + (N - 3);
}
// Driver Code
public static void Main ()
{
int N = 4, M = 4;
Console.WriteLine(steps(N, M));
}
}
Output:
Source
https://www.geeksforgeeks.org/make-array-elements-equal-in-minimum-steps/
378
Chapter 58
Input : a = { 3, 1, 1 }, b = { 1, 2, 2 }
Output : 2
Explanation : Here we can increase any 1 into 2 by 1 operation and 3 to 2 in
one decrement operation. So a[] becomes {2, 2, 1} which is a permutation of b[].
Input : a = { 3, 1, 1 }, b = { 1, 1, 2 }
Output : 1
Algorithm :
1. First sort both the arrays.
2. After sorting we will run a loop in which we compare the first and second array elements
and calculate the required operation needed to make first array equal to second.
Below is implementation of the above approach
C++
379
Chapter 58. Making elements of two arrays same with minimum increment/decrement
#include <bits/stdc++.h>
using namespace std;
return result;
}
// Driver code
int main()
{
int a[] = { 3, 1, 1 };
int b[] = { 1, 2, 2 };
int n = sizeof(a) / sizeof(a[0]);
cout << MinOperation(a, b, n);
return 0;
}
Java
380
Chapter 58. Making elements of two arrays same with minimum increment/decrement
import java.util.Arrays;
import java.io.*;
class GFG
{
static int MinOperation(int a[],
int b[],
int n)
{
// sorting both arrays
// in ascending order
Arrays.sort(a);
Arrays.sort(b);
// variable to store
// the final result
int result = 0;
return result;
}
// Driver code
public static void main (String[] args)
{
int a[] = {3, 1, 1};
int b[] = {1, 2, 2};
int n = a.length;
System.out.println(MinOperation(a, b, n));
381
Chapter 58. Making elements of two arrays same with minimum increment/decrement
}
}
PHP
<?php
// PHP program to find minimum
// increment/decrement operations
// to make array elements same.
function MinOperation($a, $b, $n)
{
// sorting both arrays in
// ascending order
sort($a);
sort($b);
// variable to store
// the final result
$result = 0;
return $result;
}
// Driver code
$a = array ( 3, 1, 1 );
382
Chapter 58. Making elements of two arrays same with minimum increment/decrement
$b = array ( 1, 2, 2 );
$n = sizeof($a);
echo MinOperation($a, $b, $n);
Output :
Source
https://www.geeksforgeeks.org/making-elements-of-two-arrays-same-with-minimum-incrementdecrement/
383
Chapter 59
Each edge is labeled with a capacity, the maximum amount of stuff that it can carry. The
goal is to figure out how much stuff can be pushed from the vertex s(source) to the vertex
t(sink).
maximum flow possible is : 23
Following are different approaches to solve the problem :
E number of edge
384
Chapter 59. Max Flow Problem Introduction
1) Initialize : max_flow = 0
f(e) = 0 for every edge 'e' in E
3) Return max_flow
Note that the path search just needs to determine whether or not there is an s-t path in the
subgraph of edges e with f(e) < C(e). This is easily done in linear time using BFS or DFS.
There is a path from source (s) to sink(t) [ s -> 1 -> 2 -> t] with maximum flow 3 unit (
path show in blue color )
385
Chapter 59. Max Flow Problem Introduction
After removing all useless edge from graph it’s look like
For above graph there is no path from source to sink so maximum flow : 3 unit But maximum
flow is 5 unit. to over come form this issue we use residual Graph.
2. Residual Graphs
The idea is to extend the naive greedy algorithm by allowing “undo” operations. For example,
from the point where this algorithm gets stuck in above image, we’d like to route two more
units of flow along the edge (s, 2), then backward along the edge (1, 2), undoing 2 of the 3
units we routed the previous iteration, and finally along the edge (1,t)
386
Chapter 59. Max Flow Problem Introduction
Source
https://www.geeksforgeeks.org/max-flow-problem-introduction/
387
Chapter 60
This problem has very simple solution, we just have to replace the minimum element arr[i]
in array by -arr[i] for current operation. In this way we can make sum of array maximum
after K operations. Once interesting case is, once minimum element becomes 0, we don’t
need to make any more changes.
C++
388
Chapter 60. Maximize array sum after K negations Set 1
// k operations.
#include<bits/stdc++.h>
using namespace std;
389
Chapter 60. Maximize array sum after K negations Set 1
Java
class GFG
{
// This function does k operations
// on array in a way that maximize
// the array sum. index --> stores
// the index of current minimum
// element for j'th operation
static int maximumSum(int arr[], int n, int k)
{
// Modify array K number of times
for (int i = 1; i <= k; i++)
{
int min = +2147483647;
int index = -1;
390
Chapter 60. Maximize array sum after K negations Set 1
// Driver program
public static void main(String arg[])
{
int arr[] = {-2, 0, 5, -1, 2};
int k = 4;
int n = arr.length;
System.out.print(maximumSum(arr, n, k));
}
}
Python3
min = +2147483647
index = -1
min = arr[j]
index = j
391
Chapter 60. Maximize array sum after K negations Set 1
# Driver program
arr = [-2, 0, 5, -1, 2]
k = 4
n = len(arr)
print(maximumSum(arr, n, k))
C#
class GFG
{
392
Chapter 60. Maximize array sum after K negations Set 1
// Driver code
public static void Main()
{
int []arr = {-2, 0, 5, -1, 2};
int k = 4;
int n = arr.Length;
Console.Write(maximumSum(arr, n, k));
}
}
PHP
<?php
// PHP program to to maximize
// array sum after k operations.
393
Chapter 60. Maximize array sum after K negations Set 1
// Driver Code
$arr = array(-2, 0, 5, -1, 2);
394
Chapter 60. Maximize array sum after K negations Set 1
$k = 4;
$n = sizeof($arr) / sizeof($arr[0]);
echo maximumSum($arr, $n, $k);
Output :
10
Source
https://www.geeksforgeeks.org/maximize-array-sun-after-k-negation-operations/
395
Chapter 61
396
Chapter 61. Maximize array sum after K negations Set 2
The implementation used in above solution uses linear search to find minimum element. The
time complexity of the above discussed solution is O(nk)
In this post an optimized solution is implemented that uses a priority queue (or binary heap)
to find minimum element quickly.
Below is Java implementation of the idea. It uses PriorityQueue class in Java.
class maximizeSum
{
public static int maxSum(int[] a, int k)
{
// Create a priority queue and insert all array elements
// int
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int x : a)
pq.add(x);
// Driver code
public static void main (String[] args)
{
int[] arr = {-2, 0, 5, -1, 2};
int k = 4;
System.out.println(maxSum(arr, k));
}
}
397
Chapter 61. Maximize array sum after K negations Set 2
Output:
10
Note that this optimized solution can be implemented in O(n + kLogn) time as we can
create a priority queue (or binary heap) in O(n) time.
Source
https://www.geeksforgeeks.org/maximize-array-sum-k-negations-set-2/
398
Chapter 62
Input : arr[] = { 4, 2, 1, 8 }
Output : 18
Rearrange given array as : { 1, 8, 2, 4 }
Sum of difference between consecutive element
= |1 - 8| + |8 - 2| + |2 - 4| + |4 - 1|
= 7 + 6 + 2 + 3
= 18.
The idea is to use Greedy Approach and try to bring elements having greater difference
closer.
Consider the sorted permutation of the given array a1 , a1 , a2 ,…., an – 1 , an such that a1 <
a2 < a3 …. < an – 1 < an .
Now, to obtain the answer having maximum sum of difference between consecutive element,
arrange element in following manner:
a1 , an , a2 , an-1 ,…., an/2 , a(n/2) + 1
We can observe that the arrangement produces the optimal answer, as all a1 , a2 , a3 ,…..,
a(n/2)-1 , an/2 are subtracted twice while a(n/2)+1 , a(n/2)+2 , a(n/2)+3 ,….., an – 1 , an are added
399
Chapter 62. Maximize sum of consecutive differences in a circular array
twice.
C++
return sum;
}
// Driver Program
int main()
{
int arr[] = { 4, 2, 1, 8 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxSum(arr, n) << endl;
return 0;
}
Java
class MaxSum
{
400
Chapter 62. Maximize sum of consecutive differences in a circular array
return sum;
}
// Driver Program
public static void main (String[] args)
{
int arr[] = { 4, 2, 1, 8 };
int n = arr.length;
System.out.println(maxSum(arr, n));
}
}
/*This code is contributed by Prakriti Gupta*/
Python3
401
Chapter 62. Maximize sum of consecutive differences in a circular array
sum -= (2 * arr[i])
sum += (2 * arr[n - i - 1])
return sum
# Driver Program
arr = [4, 2, 1, 8]
n = len(arr)
print (maxSum(arr, n))
C#
class MaxSum {
return sum;
}
// Driver Program
public static void Main()
{
int[] arr = { 4, 2, 1, 8 };
int n = arr.Length;
Console.WriteLine(maxSum(arr, n));
}
402
Chapter 62. Maximize sum of consecutive differences in a circular array
Output :
18
Source
https://www.geeksforgeeks.org/maximize-sum-consecutive-differences-circular-array/
403
Chapter 63
Input: N = 5, M = 3
CP[]= {5, 10, 35, 7, 23}
SP[] = {11, 10, 0, 9, 19}
Output: 8
Profit on 0th product i.e. 11-5 = 6
Profit on 3rd product i.e. 9-7 = 2
Selling any other product will not give profit.
So, total profit = 6+2 = 8.
Input: N = 4, M = 2
CP[] = {17, 9, 8, 20}
SP[] = {10, 9, 8, 27}
Output: 7
Approach:
1. Store the profit/loss on buying and selling of each product i.e. SP[i]-CP[i] in an
array.
2. Sort that array in descending order.
3. Add the positive values up to M values as positive values denote profit.
4. Return Sum.
404
Chapter 63. Maximize the profit by selling at-most M products
return sum;
}
// Driver Code
int main()
{
int N = 5, M = 3;
int CP[] = { 5, 10, 35, 7, 23 };
int SP[] = { 11, 10, 0, 9, 19 };
return 0;
}
Java
405
Chapter 63. Maximize the profit by selling at-most M products
class GFG
{
return sum;
}
// Driver Code
public static void main(String args[])
{
int N = 5, M = 3;
int CP[] = { 5, 10, 35, 7, 23 };
int SP[] = { 11, 10, 0, 9, 19 };
406
Chapter 63. Maximize the profit by selling at-most M products
Python3
# Python3 implementation
# of above approach
# Calculating profit
# for each gadget
for i in range(N) :
profit.append(sp[i] - cp[i])
sum = 0
return sum
# Driver Code
if __name__ == "__main__" :
N, M = 5, 3
CP = [5, 10, 35, 7, 23]
SP = [11, 10, 0, 9, 19]
# function calling
print(solve(N, M, CP, SP))
C#
407
Chapter 63. Maximize the profit by selling at-most M products
408
Chapter 63. Maximize the profit by selling at-most M products
Source
https://www.geeksforgeeks.org/maximize-the-profit-by-selling-at-most-m-products/
409
Chapter 64
Maximize the sum of X+Y elements by picking X and Y elements from 1st and 2nd array -
GeeksforGeeks
Given two arrays of size N, and two numbers X and Y, the task is to maximize the sum by
considering the below points:
• Pick x values from the first array and y values from the second array such that the
sum of X+Y values is maximum.
• It is given that X + Y is equal to N.
Examples:
Approach: A greedy approach can be used to solve the above problem. Below are the
required steps:
• Find those elements of arrays first that have maximum value by finding the highest
difference between elements of two arrays.
410
Chapter 64. Maximize the sum of X+Y elements by picking X and Y elements from 1st
and 2nd array
• For that, find the absolute difference between the value of the first and second array
and then store it in some another array.
• Sort this array in decreasing order.
• While sorting, track the original positions of elements in the arrays.
• Now compare the elements of the two arrays and add the greater value to the max-
Amount.
• If both have the same value, add an element of the first array if X is not zero else add
an element of the second array.
• After traversing the arrays completely return the maxAmount calculated.
411
Chapter 64. Maximize the sum of X+Y elements by picking X and Y elements from 1st
and 2nd array
vector<triplet> v;
int i = 0;
412
Chapter 64. Maximize the sum of X+Y elements by picking X and Y elements from 1st
and 2nd array
i++;
}
return maxAmount;
}
// Driver Code
int main()
{
int A[] = { 1, 4, 1, 2 };
int B[] = { 4, 3, 2, 5 };
int n = sizeof(A) / sizeof(A[0]);
int X = 2, Y = 2;
Output:
14
Source
https://www.geeksforgeeks.org/maximize-the-sum-of-xy-elements-by-picking-x-and-y-elements-from-1st-and-2nd-a
413
Chapter 65
Input : N = 4, arr[] = { 3, 5, 6, 1 }
Output : 31
If we arrange arr[] as { 1, 3, 5, 6 }.
Sum of arr[i]*i is 1*0 + 3*1 + 5*2 + 6*3
= 31, which is maximum
A simple solution is to generate all permutations of given array. For every permutation,
compute the value of Σarr[i]*i and finally return the maximum value.
An efficient solution is based on the fact that the largest value should be scaled maximum
and smallest value should be scaled minimum. So we multiply minimum value of i with
minimum value of arr[i]. So, sort the given array in increasing order and compute the sum
of ari]*i, where i = 0 to n-1.
Below is the implementation of this approach:
C++
414
Chapter 65. Maximize the sum of arr[i]*i
return sum;
}
// Driven Program
int main()
{
int arr[] = { 3, 5, 6, 1 };
int n = sizeof(arr)/sizeof(arr[0]);
Java
class GFG {
return sum;
}
// Driven Program
public static void main(String[] args)
{
int arr[] = { 3, 5, 6, 1 };
415
Chapter 65. Maximize the sum of arr[i]*i
int n = arr.length;
System.out.println(maxSum(arr, n));
}
}
// This code is contributed by Prerna Saini
Python3
return sum
# Driver Program
arr = [3,5,6,1]
n = len(arr)
print(maxSum(arr,n))
C#
class GFG {
416
Chapter 65. Maximize the sum of arr[i]*i
Array.Sort(arr);
return sum;
}
// Driver code
static public void Main()
{
int[] arr = {3, 5, 6, 1};
int n = arr.Length;
Console.WriteLine(maxSum(arr, n));
}
}
PHP
<?php
// PHP program to find the
// maximum value of i*arr[i]
return $sum;
}
// Driver Code
$arr = array( 3, 5, 6, 1 );
$n = count($arr);
417
Chapter 65. Maximize the sum of arr[i]*i
Output:
31
Source
https://www.geeksforgeeks.org/maximize-sum-arrii/
418
Chapter 66
#include<stdio.h>
#include<stdlib.h>
419
Chapter 66. Maximum Length Chain of Pairs DP-20
// mcl[i] now stores the maximum chain length ending with pair i
return max;
}
Java
class Pair{
int a;
int b;
420
Chapter 66. Maximum Length Chain of Pairs DP-20
// mcl[i] now stores the maximum chain length ending with pair i
return max;
}
Python3
class Pair(object):
def __init__(self, a, b):
self.a = a
self.b = b
421
Chapter 66. Maximum Length Chain of Pairs DP-20
max = 0
return max
C#
class Pair {
int a;
int b;
422
Chapter 66. Maximum Length Chain of Pairs DP-20
return max;
}
// Driver Code
public static void Main()
{
Pair []arr = new Pair[] {new Pair(5,24), new Pair(15, 25),
new Pair (27, 40), new Pair(50, 60)};
Console.Write("Length of maximum size chain is " +
maxChainLength(arr, arr.Length));
}
}
Output:
423
Chapter 66. Maximum Length Chain of Pairs DP-20
Source
https://www.geeksforgeeks.org/maximum-length-chain-of-pairs-dp-20/
424
Chapter 67
Input : array = { 2, 4, 9 }, k = 3
Output : 2
We are allowed to do at most three increments. We can make two elements 4 by
increasing 2 by 2. Note that we can not make two elements 9 as converting 4 to
9 requires 5 increments.
Input : array = { 5, 5, 3, 1 }, k = 5
Output : 3
Explanation: Here 1st and 2nd elements are equal. Then we can increase
3rd element 3 upto 5. Then k becomes (k-2) = 3. Now we can’t increase 1 to
5 because k value is 3 and we need 4 for the updation. Thus equal elements
possible are 3. Here we can also increase 1 to 5. Then also we have 3 because
we can’t update 3 to 5.
Input : array = { 5, 5, 3, 1 }, k = 6
Output : 4
Naive Approach: In the naive approach we have an algorithm in O(n^2) time in which
we check for each element how many other elements can be incremented so that they will
become equal to them.
Efficient Approach: In this approach, first we will sort the array. Then we maintain two
arrays. First is prefix sum array which stores the prefix sum of the array and another is
maxx[] array which stores the maximum element found till every point, i.e., max[i] means
425
Chapter 67. Maximum elements that can be made equal with k updates
maximum element from 1 to i. After storing these values in prefix[] array and maxx[] array,
we do the binary search from 1 to n(number of elements of the array) to calculate how many
elements which can be incremented to make them equal. In the binary search, we use one
function in which we determine what is the number of elements can be incremented to make
them equal to a single value.
C++
426
Chapter 67. Maximum elements that can be made equal with k updates
if (ElementsCalculationFunc(pre, maxx,
mid - 1, k, n)) {
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
// printing result
cout << ans << "\n";
}
int main()
{
int arr[] = { 2, 4, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
MaxNumberOfElements(arr, n, k);
return 0;
}
427
Chapter 67. Maximum elements that can be made equal with k updates
Java
import java.util.Arrays;
public class GFG {
428
Chapter 67. Maximum elements that can be made equal with k updates
int mid = (l + r) / 2;
if (ElementsCalculationFunc(pre, maxx,
mid - 1, k, n))
{
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
// printing result
System.out.print((int)ans + "\n");
}
int arr[] = { 2, 4, 9 };
int n = arr.length;
int k = 3;
MaxNumberOfElements(arr, n, k);
}
}
429
Chapter 67. Maximum elements that can be made equal with k updates
C#
class GFG {
430
Chapter 67. Maximum elements that can be made equal with k updates
pre[i] = 0;
maxx[i] = 0;
}
int mid = (l + r) / 2;
if (ElementsCalculationFunc(pre, maxx,
mid - 1, k, n))
{
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
// printing result
Console.Write ((int)ans + "\n");
}
// Driver code
public static void Main()
{
int []arr = { 2, 4, 9 };
int n = arr.Length;
int k = 3;
MaxNumberOfElements(arr, n, k);
}
431
Chapter 67. Maximum elements that can be made equal with k updates
Output:
Source
https://www.geeksforgeeks.org/maximum-elements-can-made-equal-k-updates/
432
Chapter 68
Maximum number by
concatenating every element in
a rotation of an array
Approach: On observing carefully, it is found that the number which has the largest left-
most digit in all elements will be the first element in the number. Since the concatenation
has to be done in term of rotation of arrays. Concatenate all the numbers from the largest
left most digit index to the end and then concatenate the elements from 0th index to the
largest left most digit index.
Below is the implementation of the above approach:
C++
433
Chapter 68. Maximum number by concatenating every element in a rotation of an array
434
Chapter 68. Maximum number by concatenating every element in a rotation of an array
// Driver Code
int main() {
int a[] = {54, 546, 548, 60};
int n = sizeof(a)/sizeof(a[0]);
printLargest(a,n);
return 0;
}
Java
435
Chapter 68. Maximum number by concatenating every element in a rotation of an array
// Driver Code
public static void main(String args[]) {
int a[] = { 54, 546, 548, 60 };
int n = a.length;
printLargest(a, n);
}
}
Python3
r = num%10;
num = num/10;
if(num==0):
# check for the largest left most digit
if(max<r):
r=max
ind = i;
436
Chapter 68. Maximum number by concatenating every element in a rotation of an array
# Driver Code
if __name__ == "__main__":
a = [54, 546, 548, 60]
n = len(a)
printLargest(a,n)
PHP
<?php
// PHP program to print
// the Maximum number by
// concatenating every
// element in rotation of array
// Function to print
// the largest number
function printLargest($a, $n)
{
// Iterate for
// all numbers
for($i = 0 ; $i < $n; $i++)
{
$num = $a[$i];
437
Chapter 68. Maximum number by concatenating every element in a rotation of an array
// print the
// rotation of array
for($i = $ind; $i < $n; $i++)
echo $a[$i];
// print the
// rotation of array
for($i = 0; $i < $ind; $i++)
echo $a[$i];
}
// Driver Code
$a = array (54, 546,
548, 60);
$n = sizeof($a);
printLargest($a, $n);
Output:
6054546548
438
Chapter 68. Maximum number by concatenating every element in a rotation of an array
Source
https://www.geeksforgeeks.org/maximum-number-by-concatenating-every-element-in-a-rotation-of-an-array/
439
Chapter 69
Maximum number of customers that can be satisfied with given quantity - GeeksforGeeks
A new variety of rice has been brought in supermarket and being available for the first
time, the quantity of this rice is limited. Each customer demands the rice in two different
packaging of size a and size b. The sizes a and b are decided by staff as per the demand.
Given the size of the packets a and b, the total quantity of rice available d and the number
of customers n, find out maximum number of customers that can be satisfied with the given
quantity of rice.
Display the total number of customers that can be satisfied and the index of customers that
can be satisfied.
Note: If a customer orders 2 3, he requires 2 packets of size a and 3 packets of size b.
Assume indexing of customers starts from 1.
Input:
The first line of input contains two integers n and d; next line contains two integers a and b.
Next n lines contain two integers for each customer denoting total number of bags of size a
and size b that customer requires.
Output:
Print maximum number of customers that can be satisfied and in next line print the space
separated indexes of satisfied customers.
Examples:
Input : n = 5, d = 5
a = 1, b = 1
2 0
440
Chapter 69. Maximum number of customers that can be satisfied with given quantity
3 2
4 4
10 0
0 1
Output : 2
5 1
Input : n = 6, d = 1000000000
a = 9999, b = 10000
10000 9998
10000 10000
10000 10000
70000 70000
10000 10000
10000 10000
Output : 5
1 2 3 5 6
Explanation:
In first example, the order of customers according to their demand is:
Customer ID Demand
5 1
1 2
2 5
3 8
4 10
From this, it can easily be concluded that only customer 5 and customer 1 can be satisfied
for total demand of 1 + 2 = 3. Rest of the customer cannot purchase the remaining rice, as
their demand is greater than available amount.
Approach:
In order to meet the demand of maximum number of customers we must start with the
customer with minimum demand so that we have maximum amount of rice left to satisfy
remaining customers. Therefore, sort the customers according to the increasing order of
demand so that maximum number of customers can be satisfied.
Below is the implementation of above approach:
441
Chapter 69. Maximum number of customers that can be satisfied with given quantity
vector<int> ans;
// Driver program
int main()
{
// Initializing variables
int n = 5;
long d = 5;
int a = 1, b = 1;
int arr[][2] = {{2, 0},
{3, 2},
{4, 4},
{10, 0},
{0, 1}};
solve(n, d, a, b, arr);
return 0;
442
Chapter 69. Maximum number of customers that can be satisfied with given quantity
Output:
2
5 1
Source
https://www.geeksforgeeks.org/maximum-number-customers-can-satisfied-given-quantity/
443
Chapter 70
Input : a[] = { 0, 0, 0 }
Output : 0
A simple solution is to generate all subsets, find product of every subset and return
maximum product.
A better solution is to use the below facts.
1. If there are even number of negative numbers and no zeros, result is simply product
of all
2. If there are odd number of negative numbers and no zeros, result is product of all
except the largest valued negative number.
444
Chapter 70. Maximum product subset of an array
3. If there are zeros, result is product of all except these zeros with one exceptional case.
The exceptional case is when there is one negative number and all other elements are
0. In this case, result is 0.
// If number is 0, we don't
// multiply it with product.
if (a[i] == 0) {
count_zero++;
continue;
}
445
Chapter 70. Maximum product subset of an array
return prod;
}
int main()
{
int a[] = { -1, -1, -2, 4, 3 };
int n = sizeof(a) / sizeof(a[0]);
cout << maxProductSubset(a, n);
return 0;
}
Output:
24
Source
https://www.geeksforgeeks.org/maximum-product-subset-array/
446
Chapter 71
Input : { 1, 2, 4, 8 }
Output : 18
Explanation : For the given array there are
several sequence possible
like : {2, 1, 4, 8}
{4, 2, 1, 8} and some more.
Now, the absolute difference of an array sequence will be
like for this array sequence {1, 2, 4, 8}, the absolute
difference sum is
= |1-2| + |2-4| + |4-8| + |8-1|
= 14
For the given array, we get the maximum value for
the sequence {1, 8, 2, 4}
= |1-8| + |8-2| + |2-4| + |4-1|
= 18
To solve this problem, we have to think greedily that how can we maximize the difference
value of the elements so that we can have a maximum sum. This is possible only if we
calculate the difference between some very high values and some very low values like (highest
– smallest). This is the idea which we have to use to solve this problem. Let us see the
above example, we will have maximum difference possible for sequence {1, 8, 2, 4} because
in this sequence we will get some high difference values, ( 1-8 = 7, 8-2 = 6 .. ). Here, by
447
Chapter 71. Maximum sum of absolute difference of an array
placing 8(highest element) in place of 1 and 2 we get two high difference values. Similarly,
for the other values, we will place next highest values in between other, as we have only one
left i.e 4 which is placed at last.
Algorithm: To get the maximum sum, we should have a sequence in which small and large
elements comes alternate. This is done to get maximum difference.
For the implementation of the above algorithm ->
1. We will sort the array.
2. Calculate the final sequence by taking one smallest element and largest element from the
sorted array and make one vector array of this final sequence.
3. Finally, calculate the sum of absolute difference between the elements of the array.
Below is the implementation of above idea :
C++
// CPP implementation of
// above algorithm
#include <bits/stdc++.h>
using namespace std;
448
Chapter 71. Maximum sum of absolute difference of an array
// Driver function
int main()
{
int a[] = { 1, 2, 4, 8 };
int n = sizeof(a) / sizeof(a[0]);
Java
// Java implementation of
// above algorithm
import java.io.*;
import java.util.*;
449
Chapter 71. Maximum sum of absolute difference of an array
// Driver Code
public static void main(String args[])
450
Chapter 71. Maximum sum of absolute difference of an array
{
Integer []a = { 1, 2, 4, 8 };
int n = a.length;
System.out.print(MaxSumDifference(a, n));
}
}
Python3
import numpy as np
class GFG:
def MaxSumDifference(a,n):
# sort the original array
# so that we can retrieve
# the large elements from
# the end of array elements
np.sort(a);
451
Chapter 71. Maximum sum of absolute difference of an array
# Driver Code
a = [ 1, 2, 4, 8 ]
n = len(a)
GFG.MaxSumDifference(a, n);
C#
// C# implementation of
// above algorithm
using System;
using System.Collections.Generic;
class GFG {
452
Chapter 71. Maximum sum of absolute difference of an array
// Driver Code
public static void Main()
{
int []a = { 1, 2, 4, 8 };
int n = a.Length;
Console.WriteLine(MaxSumDifference(a, n));
}
}
453
Chapter 71. Maximum sum of absolute difference of an array
Output :
18
Source
https://www.geeksforgeeks.org/maximum-sum-absolute-difference-array/
454
Chapter 72
The idea is to start picking from last array. We pick the maximum element from last array,
then we move to second last array. In second last array, we find the largest element which
is smaller than the maximum element picked from last array. We repeat this process till we
reach first array.
To obtain maximum sum we can sort all arrays and start bottom to up traversing each array
from right to left and choose a number such that it is greater then previous element. If we
are not able to select an element from array then return 0.
C++
455
Chapter 72. Maximum sum of increasing order elements from n arrays
// j = -1 means no element is
// found in a[i] so return 0
if (j == -1)
return 0;
}
return sum;
}
456
Chapter 72. Maximum sum of increasing order elements from n arrays
Java
class GFG
{
static int M = 4;
static int arr[][] = {{1, 7, 3, 4},
{4, 2, 5, 1},
{9, 5, 1, 8}};
// To calculate maximum
// sum by selecting element
// from each array
static int maximumSum(int a[][],
int n)
{
457
Chapter 72. Maximum sum of increasing order elements from n arrays
// j = -1 means no element
// is found in a[i] so
// return 0
if (j == -1)
return 0;
}
return sum;
}
// Driver Code
public static void main(String args[])
{
int n = arr.length;
System.out.print(maximumSum(arr, n));
}
}
Python3
global M;
458
Chapter 72. Maximum sum of increasing order elements from n arrays
# Selecting maximum
# element from previoulsy
# selected element
for i in range(n - 2,
-1, -1) :
for j in range(M - 1,
-1, -1) :
prev = a[i][j];
sum += prev;
break;
# j = -1 means no element
# is found in a[i] so
# return 0
if (j == -1) :
return 0;
return sum;
# Driver Code
arr = [[1, 7, 3, 4],
[4, 2, 5, 1],
[9, 5, 1, 8]];
n = len(arr) ;
print (maximumSum(arr, n));
C#
459
Chapter 72. Maximum sum of increasing order elements from n arrays
class GFG
{
static int M = 4;
// To calculate maximum
// sum by selecting
// element from each array
static int maximumSum(int[,] a,
int n)
{
int i = 0, j = 0;
460
Chapter 72. Maximum sum of increasing order elements from n arrays
break;
}
}
// j = -1 means no element
// is found in a[i] so
// return 0
if (j == -1)
return 0;
}
return sum;
}
// Driver Code
static void Main()
{
int [,]arr = new int[,]{{1, 7, 3, 4},
{4, 2, 5, 1},
{9, 5, 1, 8}};
int n = arr.GetLength(0);
Console.Write(maximumSum(arr, n));
}
}
PHP
<?php
// PHP program to find maximum
// sum by selecting a element
// from n arrays
$M = 4;
461
Chapter 72. Maximum sum of increasing order elements from n arrays
// of last array
$sum = $a[$n - 1][$M - 1];
$prev = $a[$n - 1][$M - 1];
$i; $j;
// j = -1 means no element is
// found in a[i] so return 0
if ($j == -1)
return 0;
}
return $sum;
}
// Driver Code
$arr = array(array(1, 7, 3, 4),
array(4, 2, 5, 1),
array(9, 5, 1, 8));
$n = sizeof($arr) ;
echo maximumSum($arr, $n);
Output:
18
462
Chapter 72. Maximum sum of increasing order elements from n arrays
prev = max_smaller;
sum += max_smaller;
}
return sum;
}
463
Chapter 72. Maximum sum of increasing order elements from n arrays
Output:
18
Source
https://www.geeksforgeeks.org/maximum-sum-increasing-order-elements-n-arrays/
464
Chapter 73
Input : n = 3, m = 6
Train no.| Arrival Time |Dept. Time | Platform No.
1 | 10:00 | 10:30 | 1
2 | 10:10 | 10:30 | 1
3 | 10:00 | 10:20 | 2
4 | 10:30 | 12:30 | 2
5 | 12:00 | 12:30 | 3
6 | 09:00 | 10:05 | 1
Output : Maximum Stopped Trains = 5
Explanation : If train no. 1 will left
to go without stoppage then 2 and 6 can
easily be accommodated on platform 1.
And 3 and 4 on platform 2 and 5 on platform 3.
Input : n = 1, m = 3
Train no.|Arrival Time|Dept. Time | Platform No.
1 | 10:00 | 10:30 | 1
2 | 11:10 | 11:30 | 1
465
Chapter 73. Maximum trains for which stoppage can be provided
3 | 12:00 | 12:20 | 1
If we start with a single platform only then we have 1 platform and some trains with their
arrival time and departure time and we have to maximize the number of trains on that
platform. This task is similar as Activity Selection Problem. So, for n platforms we will
simply make n-vectors and put the respective trains in those vectors according to platform
number. After that by applying greedy approach we easily solve this problem.
Note : We will take input in form of 4-digit integer for arrival and departure time as 1030
will represent 10:30 so that we may handle the data type easily.
Also, we will choose a 2-D array for input as arr[m][3] where arr[i][0] denotes arrival time,
arr[i][1] denotes departure time and arr[i][2] denotes the platform for ith train.
466
Chapter 73. Maximum trains for which stoppage can be provided
// driver function
int main()
{
int arr[m][3] = { 1000, 1030, 1,
1010, 1020, 1,
1025, 1040, 1,
1130, 1145, 2,
1130, 1140, 2 };
cout << "Maximum Stopped Trains = "
<< maxStop(arr);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/maximum-trains-stoppage-can-provided/
467
Chapter 74
Minimize Cash Flow among a given set of friends who have borrowed money from each other
- GeeksforGeeks
Given a number of friends who have to give or take some amount of money from one another.
Design an algorithm by which the total cash flow among all the friends is minimized.
Example:
Following diagram shows input debts to be settled.
468
Chapter 74. Minimize Cash Flow among a given set of friends who have borrowed money
from each other
The idea is to use Greedy algorithm where at every step, settle all amounts of one person
and recur for remaining n-1 persons.
How to pick the first person? To pick the first person, calculate the net amount for every
person where net amount is obtained by subtracting all debts (amounts to pay) from all
credits (amounts to be paid). Once net amount for every person is evaluated, find two
persons with maximum and minimum net amounts. These two persons are the most creditors
and debtors. The person with minimum of two is our first person to be settled and removed
from list. Let the minimum of two amounts be x. We pay ‘x’ amount from the maximum
debtor to maximum creditor and settle one person. If x is equal to the maximum debit,
then maximum debtor is settled, else maximum creditor is settled.
The following is detailed algorithm.
Do following for every person Pi where i is from 0 to n-1.
1) Compute the net amount for every person. The net amount for person ‘i’ can be computed
be subtracting sum of all debts from sum of all credits.
2) Find the two persons that are maximum creditor and maximum debtor. Let the maximum
amount to be credited maximum creditor be maxCredit and maximum amount to be debited
from maximum debtor be maxDebit. Let the maximum debtor be Pd and maximum creditor
be Pc.
3) Find the minimum of maxDebit and maxCredit. Let minimum of two be x. Debit ‘x’
from Pd and credit this amount to Pc
4) If x is equal to maxCredit, then remove Pc from set of persons and recur for remaining
(n-1) persons.
5) If x is equal to maxDebit, then remove Pd from set of persons and recur for
remaining (n-1) persons.
Thanks to Balaji S for suggesting this method in a comment here.
The following is implementation of above algorithm.
C++
469
Chapter 74. Minimize Cash Flow among a given set of friends who have borrowed money
from each other
#include<iostream>
using namespace std;
470
Chapter 74. Minimize Cash Flow among a given set of friends who have borrowed money
from each other
minCashFlowRec(amount);
}
471
Chapter 74. Minimize Cash Flow among a given set of friends who have borrowed money
from each other
Java
class GFG
{
// Number of persons (or vertices in the graph)
static final int N = 3;
472
Chapter 74. Minimize Cash Flow among a given set of friends who have borrowed money
from each other
473
Chapter 74. Minimize Cash Flow among a given set of friends who have borrowed money
from each other
// calculated by subtracting
// debts of 'p' from credits of 'p'
for (int p = 0; p < N; p++)
for (int i = 0; i < N; i++)
amount[p] += (graph[i][p] - graph[p][i]);
minCashFlowRec(amount);
}
// Driver code
public static void main (String[] args)
{
// graph[i][j] indicates the amount
// that person i needs to pay person j
int graph[][] = { {0, 1000, 2000},
{0, 0, 5000},
{0, 0, 0},};
Python3
minInd = 0
for i in range(1, N):
if (arr[i] < arr[minInd]):
minInd = i
return minInd
maxInd = 0
474
Chapter 74. Minimize Cash Flow among a given set of friends who have borrowed money
from each other
# A utility function to
# return minimum of 2 values
def minOf2(x, y):
475
Chapter 74. Minimize Cash Flow among a given set of friends who have borrowed money
from each other
minCashFlowRec(amount)
minCashFlowRec(amount)
# Driver code
minCashFlow(graph)
C#
class GFG
{
// Number of persons (or
// vertices in the graph)
static int N = 3;
476
Chapter 74. Minimize Cash Flow among a given set of friends who have borrowed money
from each other
477
Chapter 74. Minimize Cash Flow among a given set of friends who have borrowed money
from each other
if (amount[mxCredit] == 0 &&
amount[mxDebit] == 0)
return;
minCashFlowRec(amount);
}
// Driver code
478
Chapter 74. Minimize Cash Flow among a given set of friends who have borrowed money
from each other
Output:
Source
https://www.geeksforgeeks.org/minimize-cash-flow-among-given-set-friends-borrowed-money/
479
Chapter 75
480
Chapter 75. Minimize the maximum difference between the heights
// Initialize result
int ans = arr[n-1] - arr[0];
481
Chapter 75. Minimize the maximum difference between the heights
Java
class GFG {
482
Chapter 75. Minimize the maximum difference between the heights
if (n == 1)
return 0;
// Initialize result
int ans = arr[n-1] - arr[0];
483
Chapter 75. Minimize the maximum difference between the heights
Python3
if (n == 1):
return 0
# Initialize result
ans = arr[n-1] - arr[0]
subtract = arr[i] - k
add = arr[i] + k
484
Chapter 75. Minimize the maximum difference between the heights
# Driver function
arr = [ 4, 6 ]
n = len(arr)
k = 10
Output :
Maximum difference is 2
Source
https://www.geeksforgeeks.org/minimize-the-maximum-difference-between-the-heights/
485
Chapter 76
Minimize the sum of product of two arrays with permutations allowed - GeeksforGeeks
Given two arrays, A and B, of equal size n, the task is to find the minimum value of A[0] *
B[0] + A[1] * B[1] +…+ A[n-1] * B[n-1]. Shuffling of elements of arrays A and B is allowed.
Examples :
The idea is to multiply minimum element of one array to maximum element of another array.
Algorithm to solve this problem:
486
Chapter 76. Minimize the sum of product of two arrays with permutations allowed
return result;
}
// Driven Program
int main()
{
int A[] = { 3, 1, 1 };
int B[] = { 6, 5, 4 };
int n = sizeof(A) / sizeof(A[0]);
cout << minValue(A, B, n) << endl;
return 0;
}
Java
class GFG {
487
Chapter 76. Minimize the sum of product of two arrays with permutations allowed
Arrays.sort(A);
Arrays.sort(B);
return result;
}
// Driven Program
public static void main(String[] args)
{
int A[] = { 3, 1, 1 };
int B[] = { 6, 5, 4 };
int n = A.length;
;
System.out.println(minValue(A, B, n));
}
}
Python
return result
# Driven Program
A = [3, 1, 1]
488
Chapter 76. Minimize the sum of product of two arrays with permutations allowed
B = [6, 5, 4]
n = len(A)
print minValue(A, B, n)
C#
class GFG {
return result;
}
// Driven Program
public static void Main()
{
int[] a = { 3, 1, 1 };
int[] b = { 6, 5, 4 };
int n = a.Length;
Console.Write(minValue(a, b, n));
}
}
489
Chapter 76. Minimize the sum of product of two arrays with permutations allowed
PHP
<?php
// PHP program to calculate minimum
// sum of product of two arrays.
return $result;
}
// Driver Code
$A = array( 3, 1, 1 );
$B = array( 6, 5, 4 );
$n = sizeof($A) / sizeof($A[0]);
echo minValue($A, $B, $n) ;
Output :
23
490
Chapter 76. Minimize the sum of product of two arrays with permutations allowed
Source
https://www.geeksforgeeks.org/minimize-sum-product-two-arrays-permutations-allowed/
491
Chapter 77
Minimum Cost Path with Left, Right, Bottom and Up moves allowed - GeeksforGeeks
Given a two dimensional grid, each cell of which contains integer cost which represents a
cost to traverse through that cell, we need to find a path from top left cell to bottom right
cell by which total cost incurred is minimum.
Note : It is assumed that negative cost cycles do not exist in input matrix.
This problem is extension of below problem.
Min Cost Path with right and bottom moves allowed.
In previous problem only going right and bottom was allowed but in this problem we are
allowed to go bottom, up, right and left i.e. in all 4 direction.
Examples:
It is not possible to solve this problem using dynamic programming similar to previous
problem because here current state depends not only on right and bottom cells but also on
left and upper cells. We solve this problem using dijkstra’s algorithm. Each cell of grid
represents a vertex and neighbor cells adjacent vertices. We do not make an explicit graph
492
Chapter 77. Minimum Cost Path with Left, Right, Bottom and Up moves allowed
from these cells instead we will use matrix as it is in our dijkstra’s algorithm.
In below code Dijkstra’ algorithm’s implementation using C++ STL is used. The code
implemented below is changed to cope with matrix represented implicit graph. Please also
see use of dx and dy arrays in below code, these arrays are taken for simplifying the process
of visiting neighbor vertices of each cell.
#define ROW 5
#define COL 5
493
Chapter 77. Minimum Cost Path with Left, Right, Bottom and Up moves allowed
set<cell> st;
494
Chapter 77. Minimum Cost Path with Left, Right, Bottom and Up moves allowed
Output:
327
Source
https://www.geeksforgeeks.org/minimum-cost-path-left-right-bottom-moves-allowed/
495
Chapter 78
This problem can be solved using greedy approach, If total cost is denoted by S, then S =
a1w1 + a2w2 … + akwk, where wi is a cost of certain edge cutting and ai is corresponding
coefficient, The coefficient ai is determined by the total number of cuts we have competed
496
Chapter 78. Minimum Cost to cut a board into squares
using edge wi at the end of the cutting process. Notice that sum of the coefficients are always
constant, hence we want to find a distribution of ai obtainable such that S is minimum. To
do so we perform cuts on highest cost edge as early as possible, which will reach to
optimal S. If we encounter several edges having the same cost, we can cut any one of them
first.
Below is the solution using above approach, first we sorted the edge cutting costs in reverse
order, then we loop in them from higher cost to lower cost building our solution. Each time
we choose an edge, counter part count is incremented by 1, which is to be multiplied each
time with corresponding edge cutting cost.
Notice below used sort method, sending greater() as 3rd argument to sort method sorts
number in non-increasing order, it is predefined function of the library.
C++
497
Chapter 78. Minimum Cost to cut a board into squares
return res;
}
Java
class GFG
{
// method returns minimum cost to break board into
// m*n squares
static int minimumCostOfBreaking(Integer X[], Integer Y[],
int m, int n)
{
int res = 0;
498
Chapter 78. Minimum Cost to cut a board into squares
Arrays.sort(X, Collections.reverseOrder());
return res;
499
Chapter 78. Minimum Cost to cut a board into squares
// Driver program
public static void main(String arg[])
{
int m = 6, n = 4;
Integer X[] = {2, 1, 3, 1, 4};
Integer Y[] = {4, 1, 2};
System.out.print(minimumCostOfBreaking(X, Y, m-1, n-1));
}
}
Python3
res = 0
else:
500
Chapter 78. Minimum Cost to cut a board into squares
return res
# Driver program
m = 6; n = 4
X = [2, 1, 3, 1, 4]
Y = [4, 1, 2]
Output:
42
Source
https://www.geeksforgeeks.org/minimum-cost-cut-board-squares/
501
Chapter 79
Input : k = 4
Output : 2
Fibonacci term added twice that is
2 + 2 = 4.
Other combinations are
1 + 1 + 2.
1 + 1 + 1 + 1
Among all cases first case has the
minimum number of terms = 2.
Input : k = 17
Output : 3
We can get any sum using Fibonacci numbers as 1 is a Fibonacci number. For example to
get n, we can n times add 1. Here we need to to minimize the count of Fibonacci numbers
that contribute to sum. So this problem is basically coin change problemwith coins having
fibonacci values. By taking some examples, we can notice that With Fibonacci coin values
Greedy approach works.
Firstly we calculate Fibonacci terms till less than or equal to k. then start from the last
term and keep subtracting that term from k until k >(nth term). Also along with this keep
increasing the count of the number of terms.
502
Chapter 79. Minimum Fibonacci terms with sum equal to K
When k < (nth Fibonacci term) move to next Fibonacci term which is less than or Equal
to k. at last, print the value of count.
The stepwise algorithm is:
// Greedy step
count += K / (fibo[j]) // Note that division
// is repeated subtraction.
K = K % (fibo[j])
j--;
5. Print count.
fiboTerms.push_back(nextTerm);
i++;
}
}
503
Chapter 79. Minimum Fibonacci terms with sum equal to K
calcFiboTerms(fiboTerms, K);
j--;
}
return count;
}
// driver code
int main()
{
int K = 17;
return 0;
}
Java
class GFG
{
// Function to calaculate Fibonacci Terms
public static void calcFiboTerms(ArrayList<Integer> fiboterms,
504
Chapter 79. Minimum Fibonacci terms with sum equal to K
int k)
{
int i = 3, nextTerm = 0;
fiboterms.add(0);
fiboterms.add(1);
fiboterms.add(1);
fiboterms.add(nextTerm);
i++;
}
}
j--;
}
return count;
}
505
Chapter 79. Minimum Fibonacci terms with sum equal to K
// driver code
public static void main (String[] args) {
int k = 17;
System.out.println(fibMinTerms(k));
}
}
Output:
Source
https://www.geeksforgeeks.org/minimum-fibonacci-terms-sum-equal-k/
506
Chapter 80
We need to find the maximum number of trains that are there on the given railway station
at a time. A Simple Solution is to take every interval one by one and find the number
of intervals that overlap with it. Keep track of maximum number of intervals that overlap
with an interval. Finally return the maximum value. Time Complexity of this solution is
O(n2 ).
We can solve the above problem in O(nLogn) time. The idea is to consider all events in
sorted order. Once we have all events in sorted order, we can trace the number of trains at
any time keeping track of trains that have arrived, but not departed.
For example consider the above example.
507
Chapter 80. Minimum Number of Platforms Required for a Railway/Bus Station
Following is the implementation of above approach. Note that the implementation doesn’t
create a single sorted list of all events, rather it individually sorts arr[] and dep[] arrays, and
then uses merge process of merge sort to process them together as a single sorted array.
Note : This approach assumes that trains are arriving and departing on same date.
C++
508
Chapter 80. Minimum Number of Platforms Required for a Railway/Bus Station
return result;
}
Java
import java.util.*;
class GFG {
509
Chapter 80. Minimum Number of Platforms Required for a Railway/Bus Station
return result;
}
510
Chapter 80. Minimum Number of Platforms Required for a Railway/Bus Station
Python3
# plat_needed indicates
# number of platforms
# needed at a time
plat_needed = 1
result = 1
i = 1
j = 0
# Similar to merge in
# merge sort to process
# all events in sorted order
while (i < n and j < n):
plat_needed+=1
i+=1
plat_needed-=1
511
Chapter 80. Minimum Number of Platforms Required for a Railway/Bus Station
j+=1
return result
# driver code
C#
class GFG {
512
Chapter 80. Minimum Number of Platforms Required for a Railway/Bus Station
return result;
}
PHP
<?php
// PHP Program to find minimum number
// of platforms required on a railway
// station
513
Chapter 80. Minimum Number of Platforms Required for a Railway/Bus Station
// plat_needed indicates
// number of platforms
// needed at a time
$plat_needed = 1;
$result = 1;
$i = 1;
$j = 0;
// Similar to merge in
// merge sort to process
// all events in sorted order
while ($i < $n and $j < $n)
{
return $result;
}
// Driver Code
514
Chapter 80. Minimum Number of Platforms Required for a Railway/Bus Station
Output:
Source
https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/
515
Chapter 81
Input : []][][
Output : 2
First swap: Position 3 and 4
[][]][
Second swap: Position 5 and 6
[][][]
Input : [[][]]
Output : 0
String is already balanced.
We can solve this problem using greedy strategies. If the first X characters form a balanced
string, we can neglect these characters and continue on. If we encounter a ‘]’ before the
required ‘[‘, then we must start swapping elements to balance the string.
Naive Approach
Initialize sum = 0 where sum stores result. Go through the string maintaining a count of
the number of ‘[‘ brackets encountered. Reduce this count when we encounter a ‘]’ character.
If the count hits negative, then we must start balancing the string.
Let index ‘i’ represents the position we are at. We now move forward to the next ‘[‘ at
516
Chapter 81. Minimum Swaps for Bracket Balancing
index j. Increase sum by j – i. Move the ‘[‘ at position j, to position i, and shift all other
characters to the right. Set the count back to 0 and continue traversing the string. At the
end ‘sum’ will have the required value.
Time Complexity = O(N^2)
Extra Space = O(1)
Optimized approach
We can initially go through the string and store the positions of ‘[‘ in a vector say ‘pos‘.
Initialize ‘p’ to 0. We shall use p to traverse the vector ‘pos’. Similar to the naive approach,
we maintain a count of encountered ‘[‘ brackets. When we encounter a ‘[‘ we increase the
count, and increase ‘p’ by 1. When we encounter a ‘]’ we decrease the count. If the count
ever goes negative, this means we must start swapping. The element pos[p] tells us the
index of the next ‘[‘. We increase the sum by pos[p] – i, where i is the current index. We
can swap the elements in the current index and pos[p] and reset count to 0.
Since we have converted a step that was O(N) in the naive approach, to an O(1) step, our
new time complexity reduces.
Time Complexity = O(N)
Extra Space = O(N)
517
Chapter 81. Minimum Swaps for Bracket Balancing
--count;
// Reset count to 1
count = 1;
}
}
return sum;
}
// Driver code
int main()
{
string s = "[]][][";
cout << swapCount(s) << "\n";
s = "[[][]]";
cout << swapCount(s) << "\n";
return 0;
}
Output:
2
0
Source
https://www.geeksforgeeks.org/minimum-swaps-bracket-balancing/
518
Chapter 82
Minimum cost for acquiring all coins with k extra coins allowed with every coin - Geeks-
forGeeks
You are given a list of N coins of different denominations. you can pay an amount equivalent
to any 1 coin and can acquire that coin. In addition, once you have paid for a coin, we can
choose at most K more coins and can acquire those for free. The task is to find the minimum
amount required to acquire all the N coins for a given value of K.
Examples :
As per question, we can see that at a cost of 1 coin, we can acquire at most K+1 coins.
Therefore, in order to acquire all the n coins, we will be choosing ceil(n/(k+1)) coins and
the cost of choosing coins will be minimum if we choose smallest ceil(n/(k+1)) ( Greedy
approach). Smallest ceil(n/(k+1)) coins can be found by simply sorting all the N values in
increasing order.
If we should check for time complexity (n log n) is for sorting element and (k) is for adding
the total amount. So, finally Time Complexity : O(n log n).
C++
519
Chapter 82. Minimum cost for acquiring all coins with k extra coins allowed with every
coin
// calculate no. of
// coins needed
int coins_needed = ceil(1.0 * n /
(k + 1));
// calculate sum of
// all selected coins
int ans = 0;
for (int i = 0; i <= coins_needed - 1;
i++)
ans += coin[i];
return ans;
}
// Driver Code
int main()
{
int coin[] = {8, 5, 3, 10,
2, 1, 15, 25};
int n = sizeof(coin) / sizeof(coin[0]);
int k = 3;
cout << minCost(coin, n, k);
return 0;
}
Java
class GFG
{
520
Chapter 82. Minimum cost for acquiring all coins with k extra coins allowed with every
coin
// calculate no. of
// coins needed
int coins_needed = (int)Math.ceil(1.0 *
n / (k + 1));
// calculate sum of
// all selected coins
int ans = 0;
return ans;
}
// Driver code
public static void main(String arg[])
{
int coin[] = { 8, 5, 3, 10,
2, 1, 15, 25 };
int n = coin.length;
int k = 3;
System.out.print(minCost(coin, n, k));
}
}
Python3
# Python program to
# acquire all n coins
import math
521
Chapter 82. Minimum cost for acquiring all coins with k extra coins allowed with every
coin
# calculate no. of
# coins needed
coins_needed = math.ceil(1.0 * n //
(k + 1));
return ans
# Driver code
coin = [8, 5, 3, 10,
2, 1, 15, 25]
n = len(coin)
k = 3
print(minCost(coin, n, k))
C#
class GFG
{
// calculate sum of
// all selected coins
int ans = 0;
522
Chapter 82. Minimum cost for acquiring all coins with k extra coins allowed with every
coin
return ans;
}
// Driver code
public static void Main()
{
int []coin = {8, 5, 3, 10,
2, 1, 15, 25};
int n = coin.Length;
int k = 3;
// Function calling
Console.Write(minCost(coin, n, k));
}
}
PHP
<?php
// PHP program to acquire all n coins
// calculate sum of
// all selected coins
$ans = 0;
for ($i = 0; $i <= $coins_needed - 1; $i++)
$ans += $coin[$i];
return $ans;
}
// Driver Code
{
523
Chapter 82. Minimum cost for acquiring all coins with k extra coins allowed with every
coin
Output :
Note that there are more efficient approaches to find given number of smallest values. For
example, method 6 of m largest(or smallest) elements in an array can find m’th smallest
element in (n-m) Log m + m Log m).
How to handle multiple queries for a single predefined array?
In the case, if you are asked to find the above answer for many different values of K, you
have to compute it fast and our time complexity got increased as per number of queries
for k. For the purpose to serve, we can maintain a prefix sum array after sorting all the N
values and can answer queries easily and quickly.
Suppose
C++
524
Chapter 82. Minimum cost for acquiring all coins with k extra coins allowed with every
coin
// Driver Code
int main()
{
int coin[] = {8, 5, 3, 10,
2, 1, 15, 25};
int n = sizeof(coin) / sizeof(coin[0]);
preprocess(coin, n);
int k = 3;
cout << minCost(coin, n, k) << endl;
k = 7;
cout << minCost(coin, n, k) << endl;
return 0;
}
Java
525
Chapter 82. Minimum cost for acquiring all coins with k extra coins allowed with every
coin
// Driver Code
static public void main (String[] args)
{
int []coin = {8, 5, 3, 10, 2, 1, 15, 25};
int n = coin.length;
preprocess(coin, n);
int k = 3;
System.out.println(minCost(coin, n, k));
k = 7;
System.out.println( minCost(coin, n, k));
}
}
C#
526
Chapter 82. Minimum cost for acquiring all coins with k extra coins allowed with every
coin
// Driver Code
static public void Main ()
{
int []coin = {8, 5, 3, 10, 2, 1, 15, 25};
int n = coin.Length;
preprocess(coin, n);
int k = 3;
Console.WriteLine(minCost(coin, n, k));
k = 7;
Console.WriteLine( minCost(coin, n, k));
}
}
Output :
3
1
Source
https://www.geeksforgeeks.org/minimum-cost-for-acquiring-all-coins-with-k-extra-coins-allowed-with-every-coin/
527
Chapter 83
Method: Here we have to connect all the cities by path which will cost us least. The way
to do that is to find out the Minimum Spanning Tree(MST) of the map of the cities(i.e.
528
Chapter 83. Minimum cost to connect all cities
each city is a node of the graph and all the damaged roads between cities are edges). And
the total cost is the addition of the path edge values in the Minimum Spanning Tree.
Prerequisite: MST Prim’s Algorithm
C++
\
529
Chapter 83. Minimum cost to connect all cities
// Utility Program:
int main() {
530
Chapter 83. Minimum cost to connect all cities
// Input 1
int n1 = 5;
vector<vector<int>> city1 = {{0, 1, 2, 3, 4},
{1, 0, 5, 0, 7},
{2, 5, 0, 6, 0},
{3, 0, 6, 0, 0},
{4, 7, 0, 0, 0}};
findcost(n1, city1);
// Input 2
int n2 = 6;
vector<vector<int>> city2 = {{0, 1, 1, 100, 0, 0},
{1, 0, 1, 0, 0, 0},
{1, 1, 0, 0, 0, 0},
{100, 0, 0, 0, 2, 2},
{0, 0, 0, 2, 0, 2},
{0, 0, 0, 2, 2, 0}};
findcost(n2, city2);
return 0;
}
Output:
10
106
Complexity: The outer loop(i.e. the loop to add new node to MST) runs n times and in
each iteration of the loop it takes O(n) time to find the minnode and O(n) time to update
the neighboring nodes of u-th node. Hence the overall complexity is O(n2 )
Source
https://www.geeksforgeeks.org/minimum-cost-connect-cities/
531
Chapter 84
Input: 4 3 2
Output: 4
Explanation:
Choose (4, 2) so 4 is removed, new array
= {2, 3}. Now choose (2, 3) so 3 is removed.
So total cost = 2 + 2 = 4
Input: 3 4
Output: 3
Explanation: choose 3, 4, so cost is 3.
The idea is to always pick minimum value as part of the pair and remove larger value. This
minimizes cost of reducing array to size 1.
Below is the implementation of the above approach:
CPP
532
Chapter 84. Minimum cost to make array size 1 by removing larger of pairs
Java
533
Chapter 84. Minimum cost to make array size 1 by removing larger of pairs
int []a = { 4, 3, 2 };
int n = a.length;
System.out.println(cost(a, n));
}
}
Python3
# driver code
a = [ 4, 3, 2 ]
n = len(a)
print(cost(a, n))
C#
534
Chapter 84. Minimum cost to make array size 1 by removing larger of pairs
int []a = { 4, 3, 2 };
int n = a.Length;
Console.WriteLine(cost(a, n));
}
}
PHP
<?php
// PHP program to find minimum cost to
// reduce array size to 1,
// function to calculate
// the minimum cost
function cost($a, $n)
{
// Driver Code
$a = array(4, 3, 2);
$n = count($a);
echo cost($a, $n);
Output:
535
Chapter 84. Minimum cost to make array size 1 by removing larger of pairs
Source
https://www.geeksforgeeks.org/minimum-cost-make-array-size-1-removing-larger-pairs/
536
Chapter 85
Input : n = 3, m = 31,
arr = {7, 11, 17, 10, 7, 10, 2, 9, 2, 18, 8, 10, 20, 10, 3, 20,
17, 17, 17, 1, 15, 10, 8, 3, 3, 18, 13, 2, 10, 10, 11}
Output : 18
537
Chapter 85. Minimum cost to process m tasks where switching costs
Explanation (for 1st sample I/O) : Here total number of cores are 3. Let, A, B and C.
First assign task of type 1 in any of the cores -> cost 1 unit. States: A – 1, B – None, C –
None. Assign task of type 2 in any of the rest 2 cores -> cost 1 unit. States : A – 1, B – 2,
C – None. Then assign task of type 1 in that core where task of type 1 is ongoing -> cost
0 unit. States : A – 1, B – 2, C – None.
Assign task of type 3 in the free core -> cost 1 unit. States : A – 1, B – 2, C – 3.
Now, all the cores are running a task. So we have to assign task of type 4 in one of these
cores. Let’s load it in the core B, where previously type 2 task was going on -> cost 1 unit.
States: A – 1, B – 4, C – 3. Now, load the type 1 task in the core A, where type 1 task is
running -> cost 0 unit. States: A – 1, B – 4, C – 3. Hence, total cost = 1 + 1 + 0 + 1 + 1
+0=4u
units.
Explanation 2 (for 2nd sample I/O) : Total number of cores are 2. Let A and B. First
process task of type 1 in any of the cores -> cost 1 unit. States: A – 1, B – None. Process
task of type 2 in any of the rest 2 cores -> cost 1 unit. States: A – 1, B – 2. Then process
task of type 1 in that core where task of type 1 is ongoing -> cost 0 unit. States : A – 1, B
– 2. Now, let’s assign task of type 3 to core A -> cost 1 unit. States : A – 3, B – 2. Now,
assign type 2 task in core B, where already type 2 task is going on -> cost 0 unit. States :
A – 3, B – 2. Hence, total cost = 1 + 1 + 0 + 1 + 1 = 4 unit. Last assign type 1 task in
any of the cores(say A) -> cost 1 unit. States : A – 1, B – 2. Hence, total cost = 1 + 1 +
0 + 1 + 0 + 1 = 4 units.
Approach : Dividing this problem into two cases :
First one is when same type of task is currently running in one of the cores. Then, just
assign the upcoming task to that core. For example 1, at i = 3(third task), when type 1
task comes then we can assign that task to that core where previously type 1 task was going
on. Cost of this is 0 unit.
Second case is when the same type of task is not running in any of the cores. Then, there
may be two possibilities. Sub-case 1 is, if there is at least one free core then assign the
upcoming task to that core.
Sub-case 2 is, if there are no free core then we have to stop processing one type of task, free
up a core and assign the upcoming task in that core such that the cost in future becomes
minimum. To minimize cost we should stop one type of task which will never occur again
in future. If every ongoing task reoccurs at least once in future, then we should stop that
task which will reoccur last among all the currently ongoing tasks(it is a greedy approach
and will task).
For example 2 : at i = 4(fourth task), type 3 task, currently ongoing type 1 and type 2
tasks in two cores, we can stop task type 1 or task type 2 to start task type 3. But we will
stop task type 1 as type 1 task rehappens after type two task.
538
Chapter 85. Minimum cost to process m tasks where switching costs
return maxipos;
}
539
Chapter 85. Minimum cost to process m tasks where switching costs
540
Chapter 85. Minimum cost to process m tasks where switching costs
isRunning[ele] = true;
}
541
Chapter 85. Minimum cost to process m tasks where switching costs
// Driver Program
int main()
{
// Test case 1
int n1 = 3;
int m1 = 6;
vector<int> arr1{ 1, 2, 1, 3, 4, 1 };
cout << mincost(n1, m1, arr1) << endl;
// Test case 2
int n2 = 2;
int m2 = 6;
vector<int> arr2{ 1, 2, 1, 3, 2, 1 };
cout << mincost(n2, m2, arr2) << endl;
// Test case 3
int n3 = 3;
int m3 = 31;
vector<int> arr3{ 7, 11, 17, 10, 7, 10, 2, 9,
2, 18, 8, 10, 20, 10, 3, 20,
17, 17, 17, 1, 15, 10, 8, 3,
3, 18, 13, 2, 10, 10, 11 };
cout << mincost(n3, m3, arr3) << endl;
return 0;
}
Output:
4
4
18
542
Chapter 85. Minimum cost to process m tasks where switching costs
Source
https://www.geeksforgeeks.org/minimum-cost-to-process-m-tasks-where-switching-costs/
543
Chapter 86
Simple Approach: A simple approach would be to try against all combinations of array
elements and check against each set of combination difference between the group with the
highest sum and the one with lowest sum. A total of n*(n-1)/2 such groups would be formed
(nC2).
544
Chapter 86. Minimum difference between groups of size two
Time Complexity : O(n^3) To generate groups n^2 iterations will be needed and to check
against each group n iterations will be needed and hence n^3 iterations will be needed in
worst case.
Efficient Approach: Efficient approach would be to use the greedy approach. Sort the
whole array and generate groups by selecting one element from the start of the array and
one from the end.
ll calculate(ll a[], ll n)
{
// Sorting the whole array.
sort(a, a + n);
int main()
{
ll a[] = { 2, 6, 4, 3 };
int n = sizeof(a) / (sizeof(a[0]));
cout << calculate(a, n) << endl;
return 0;
}
Output:
545
Chapter 86. Minimum difference between groups of size two
Source
https://www.geeksforgeeks.org/minimum-difference-between-groups-of-size-two/
546
Chapter 87
This problem can be solved assuming a different version of the given graph. In this version
we make a reverse edge corresponding to every edge and we assign that a weight 1 and
assign a weight 0 to original edge. After this modification above graph looks something like
below,
547
Chapter 87. Minimum edges to reverse to make path from a source to a destination
Now we can see that we have modified the graph in such a way that, if we move towards
original edge, no cost is incurred, but if we move toward reverse edge 1 cost is added. So if
we apply Dijkstra’s shortest path on this modified graph from given source, then that will
give us minimum cost to reach from source to destination i.e. minimum edge reversal from
source to destination.
Below is the code based on above concept.
548
Chapter 87. Minimum edges to reverse to make path from a source to a destination
public:
Graph(int V); // Constructor
549
Chapter 87. Minimum edges to reverse to make path from a source to a destination
// Updating distance of v
dist[v] = dist[u] + weight;
setds.insert(make_pair(dist[v], v));
}
}
}
return dist;
}
550
Chapter 87. Minimum edges to reverse to make path from a source to a destination
{
Graph g(V);
for (int i = 0; i < E; i++)
{
// original edge : weight 0
g.addEdge(edge[i][0], edge[i][1], 0);
int minEdgeToReverse =
getMinEdgeReversal(edge, E, V, 0, 6);
if (minEdgeToReverse != -1)
cout << minEdgeToReverse << endl;
else
cout << "Not possible" << endl;
return 0
}
551
Chapter 87. Minimum edges to reverse to make path from a source to a destination
Output:
Source
https://www.geeksforgeeks.org/minimum-edges-reverse-make-path-source-destination/
552
Chapter 88
Minimum increment by k
operations to make all elements
equal
To solve this question we require to check whether all elements can became equal or not and
that too only by incrementing k from elements value. For this we have to check that the
difference of any two elements should always be divisible by k. If it is so, then all elements
can become equal otherwise they can not became equal in any case by incrementing k from
them. Also, the number of operations required can be calculated by finding value of (max
– Ai)/k for all elements. where max is maximum element of array.
Algorithm :
553
Chapter 88. Minimum increment by k operations to make all elements equal
return res;
C++
// return result
return res;
}
// driver program
int main()
{
554
Chapter 88. Minimum increment by k operations to make all elements equal
Java
class GFG {
// function for calculating min operations
static int minOps(int arr[], int n, int k)
{
// max elements of array
Arrays.sort(arr);
int max = arr[arr.length - 1];
int res = 0;
// return result
return res;
}
// Driver program
public static void main(String[] args)
{
int arr[] = { 21, 33, 9, 45, 63 };
int n = arr.length;
int k = 6;
System.out.println(minOps(arr, n, k));
}
}
555
Chapter 88. Minimum increment by k operations to make all elements equal
Python3
# return result
return int(res)
# driver program
arr = [21, 33, 9, 45, 63]
n = len(arr)
k = 6
print(minOps(arr, n, k))
C#
class GFG {
556
Chapter 88. Minimum increment by k operations to make all elements equal
// return result
return res;
}
// Driver program
public static void Main()
{
int[] arr = { 21, 33, 9, 45, 63 };
int n = arr.Length;
int k = 6;
Console.Write(minOps(arr, n, k));
}
}
PHP
<?php
// Program to make all array equal
557
Chapter 88. Minimum increment by k operations to make all elements equal
// return result
return $res;
}
// Driver Code
$arr = array(21, 33, 9, 45, 63);
$n = count($arr);
$k = 6;
print (minOps($arr, $n, $k));
Output :
24
Source
https://www.geeksforgeeks.org/minimum-increment-k-operations-make-elements-equal/
558
Chapter 89
Minimum increment/decrement
to make array non-Increasing
Brute-Force approach : We consider both possibilities for every element and find the
minimum of two possibilities.
Efficient Approach : Calculate the sum of absolute differences between the final array
elements and the current array elements. Thus, the answer will be the sum of the difference
559
Chapter 89. Minimum increment/decrement to make array non-Increasing
between the ith element and the smallest element occurred till then. For this, we can
maintain a min-heap to find the smallest element encountered till now. In the min-priority
queue, we will put the elements and new elements are compared with the previous minimum.
If new minimum is found we will update it, this is done because each of the next element
which is coming should be smaller than the current minimum element found till. Here, we
calculate the difference so that we can get how much we have to change the current number
so that it will be equal or less than previous numbers encountered till. Lastly, the sum of
all these difference will be our answer as this will give the final value upto which we have
to change the elements.
Below is C++ implementation of the above approach
// min heap
priority_queue<int, vector<int>, greater<int> > pq;
return sum;
}
// Driver Code
int main()
{
560
Chapter 89. Minimum increment/decrement to make array non-Increasing
int a[] = { 3, 1, 2, 1 };
int n = sizeof(a) / sizeof(a[0]);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/minimum-incrementdecrement-to-make-array-non-increasing/
561
Chapter 90
Minimum initial vertices to traverse whole matrix with given conditions - GeeksforGeeks
We are given a matrix that contains different values in its each cell. Our aim is to find the
minimal set of positions in the matrix such that entire matrix can be traversed starting from
the positions in the set.
We can traverse the matrix under below conditions:
• We can move only to those neighbors that contain value less than or to equal to the
current cell’s value. A neighbor of cell is defined as the cell that shares a side with the
given cell.
Examples:
Input : 1 2 3
2 3 1
1 1 1
Output : 1 1
0 2
If we start from 1, 1 we can cover 6
vertices in the order 1, 1 -> 1, 0 -> 2, 0
-> 2, 1 -> 2, 2 -> 1, 2. We cannot cover
the entire matrix with this vertex. Remaining
vertices can be covered 0, 2 -> 0, 1 -> 0, 0.
Input : 3 3
1 1
562
Chapter 90. Minimum initial vertices to traverse whole matrix with given conditions
Output : 0 1
If we start from 0, 1, we can traverse
the entire matrix from this single vertex
in this order 0, 0 -> 0, 1 -> 1, 1 -> 1, 0.
Traversing the matrix in this order
satisfies all the conditions stated above.
From the above examples, we can easily identify that in order to use minimum number of
positions we have to start from the positions having highest cell value. Therefore we pick the
positions that contain the highest value in the matrix. We take the vertices having highest
value in separate array. We perform DFS on every vertex starting from the highest value.
If we encounter any unvisited vertex during dfs then we have to include this vertex in our
set. When all the cells have been processed then the set contains the required vertices.
How does this work?
We need to visit all vertices and to reach largest values we must start with them. If two
largest values are not adjacent, then both of them must be picked. If two largest values are
adjacent, then any of them can be picked as moving to equal value neighbors is allowed.
563
Chapter 90. Minimum initial vertices to traverse whole matrix with given conditions
!visit[n][m + 1])
dfs(n, m + 1, visit, adj, N, M);
564
Chapter 90. Minimum initial vertices to traverse whole matrix with given conditions
// Driver code
int main()
{
int N = 2, M = 2;
Output:
0 1
Source
https://www.geeksforgeeks.org/minimum-initial-vertices-traverse-whole-matrix-given-conditions/
565
Chapter 91
Minimum number of adjacent swaps for arranging similar elements together - GeeksforGeeks
Given an array of 2 * N positive integers where each array element lies between 1 to N and
appears exactly twice in the array. The task is to find the minimum number of adjacent
swaps required to arrange all similar array elements together.
Note: It is not necessary that the final array (after performing swaps) should be sorted.
Examples:
Input: arr[] = { 1, 2, 3, 3, 1, 2 }
Output: 5
After first swapping, array will be arr[] = { 1, 2, 3, 1, 3, 2 },
after second arr[] = { 1, 2, 1, 3, 3, 2 }, after third arr[] = { 1, 1, 2, 3, 3, 2 },
after fourth arr[] = { 1, 1, 2, 3, 2, 3 }, after fifth arr[] = { 1, 1, 2, 2, 3, 3 }
Input: arr[] = { 1, 2, 1, 2 }
Output: 1
arr[2] can be swapped with arr[1] to get the required position.
Approach : This problem can be solved using greedy approach. Following are the steps :
1. Keep an array visited[] which tells that visited[curr_ele] is false if swap operation has
not been performed on curr_ele.
2. Traverse through the original array and if the current array element has not been
visited yet i.e. visited[arr[curr_ele]] = false, set it to true and iterate over another
loop starting from the current position to the end of array.
566
Chapter 91. Minimum number of adjacent swaps for arranging similar elements together
3. Initialize a variable count which will determine the number of swaps required to place
the current element’s partner at its correct position.
4. In nested loop, increment count only if the visited[curr_ele] is false (since if it is true,
means curr_ele has already been placed at its correct position).
5. If the current element’s partner is found in the nested loop, add up the value of count
to the total answer.
#include <bits/stdc++.h>
using namespace std;
int minimumSwaps = 0;
memset(visited, false, sizeof(visited));
567
Chapter 91. Minimum number of adjacent swaps for arranging similar elements together
minimumSwaps += count;
}
}
}
return minimumSwaps;
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 3, 3, 1, 2 };
int N = sizeof(arr) / sizeof(arr[0]);
N /= 2;
Output:
Source
https://www.geeksforgeeks.org/minimum-number-of-adjacent-swaps-for-arranging-similar-elements-together/
568
Chapter 92
Input :
N=3
D1[] = {5, 3, 4}
D2[] = {2, 1, 2}
Output : 2
Explanation:
3 works are to be completed. The first value on Line(i) is D1(i) and the second
value is D2(i) where D2(i) < D1(i). The smart worker can finish the second work
on Day 1 and then both third work and first work in Day 2, thus maintaining
the non-decreasing order of D1[], [3 4 5].
Input :
N=6
D1[] = {3, 3, 4, 4, 5, 5}
D2[] = {1, 2, 1, 2, 4, 4}
Output : 4
569
Chapter 92. Minimum number of days required to complete the work
Approach: The solution is greedy. The work(i) can be sorted by increasing D1[i], breaking
the ties by increasing D2[i]. If we consider the works in this order, we can try to finish the
works as early as possible. First of all complete the first work on D2[1]. Move to the second
work. If we can complete it on day D2[2] such that (D2[1]<=D2[2]), do it. Otherwise, do
the work on day D[2]. Repeat the process until we complete the N-th work, keeping the day
of the latest work.
Below is the implementation of the above approach
C++
#include <bits/stdc++.h>
using namespace std;
#define inf INT_MAX
// Driver Code
int main()
{
570
Chapter 92. Minimum number of days required to complete the work
// Number of works
int N = 3;
// D1[i]
int D1[] = { 6, 5, 4 };
// D2[i]
int D2[] = { 1, 2, 3 };
return 0;
}
Java
// Java program to find the minimum
// number days required
import java.util.*;
import java.lang.*;
import java.io.*;
// pair class for number of days
class Pair
{
int x, y;
Pair(int a, int b)
{
this.x = a;
this.y = b;
}
}
class GFG
{
static int inf = Integer.MIN_VALUE;
// Function to find the minimum
// number days required
public static int minimumDays(int N, int D1[],
int D2[])
{
// initialising ans to
// least value possible
int ans = -inf;
ArrayList
list = new ArrayList();
for (int i = 0; i < N; i++) list.add(new Pair(D1[i], D2[i])); // sort by first i.e D(i) Collec-
tions.sort(list, new Comparator()
571
Chapter 92. Minimum number of days required to complete the work
{
@Override
public int compare(Pair p1, Pair p2)
{
return p1.x – p2.x;
}
});
// Calculate the minimum possible days
for (int i = 0; i < N; i++) { if (list.get(i).y >= ans)
ans = list.get(i).y;
else
ans = list.get(i).x;
}
return ans;
}
// Driver Code
public static void main (String[] args)
{
// Number of works
int N = 3;
// D1[i]
int D1[] = new int[]{6, 5, 4};
// D2[i]
int D2[] = new int[]{1, 2, 3};
System.out.print(minimumDays(N, D1, D2));
}
}
// This code is contributed by Kirti_Mangal
Output:
Improved By : Kirti_Mangal
Source
https://www.geeksforgeeks.org/minimum-number-of-days-required-to-complete-the-work/
572
Chapter 93
Perform any one of the operations on all elements in the array. The task is to find the
minimum number of operations(addition and subtraction) that can be performed on the
sequence, in order to convert it into a Geometric Progression. If it is not possible to generate
a GP by performing the above operations, print -1.
Examples:
1. Keep a1 unchanged
2. Add one to a2 .
3. Keep a3 unchanged
4. Subtract one from a4 .
573
Chapter 93. Minimum number of operations to convert a given sequence into a Geometric
Progression
Approach The key observation to be made here is that any Geometric Progression is
uniquely determined by only its first two elements (Since the ratio between each of the next
pairs has to be the same as the ratio between this pair, consisting of the first two elements).
Since only 3*3 permutations are possible. The possible combination of operations are (+1,
+1), (+1, 0), (+1, -1), (-1, +1), (-1, 0), (-1, -1), (0, +1), (0, 0) and (0, -1). Using brute
force all these 9 permutations and checking if they form a GP in linear time will give us the
answer. The minimum of the operations which result in combinations which are in GP will
be the answer.
Below is the implementation of the above approach:
574
Chapter 93. Minimum number of operations to convert a given sequence into a Geometric
Progression
// possible operations.
int c[] = { -1, 0, 1 };
// Size of c
int possiblities = 3;
// candidate answer
int pos1 = -1, pos2 = -1;
if (a1 == 0 || a2 == 0)
continue;
575
Chapter 93. Minimum number of operations to convert a given sequence into a Geometric
Progression
}
}
// update answer
if (temp < ans) {
ans = temp;
pos1 = a1;
pos2 = a2;
}
}
}
if (ans == -1) {
cout << "-1";
return;
}
cout << "Minimum Number of Operations are " << ans << "\n";
pair<double, double> ans_pair = { pos1, pos2 };
// Driver Code
int main()
{
Output:
576
Chapter 93. Minimum number of operations to convert a given sequence into a Geometric
Progression
Source
https://www.geeksforgeeks.org/minimum-number-of-operations-to-convert-a-given-sequence-into-a-geometric-progr
577
Chapter 94
Input : a = { 4, 5, 6 }, k = 5
Output : 2
Explanation : We can increase 4 by 1 so that it becomes 5 and decrease 6 by 1 so that it becomes
Input : a = { 4, 9, 6 }, k = 5
Output : 3
Explanation :Just like previous example we can increase and decrease 4 and 6 by 1 and increase 9
Here we have to make the gcd of the array equal or multiple to k, which means there will be
cases in which all the elements are near are greater than k or is near to some of its multiple.
So, to solve this we just have to make each array value equal to or multiple to K. By doing
this we will achieve our solution, as if every element is multiple of k then it’s GCD will be
atleast K. Now our next target is to convert the array elements in the minimum operation
i.e. minimum number of increment and decrement. This minimum value of increment or
decrement can be known only by taking the remainder of each number from K i.e. either
we have to take the remainder value or (k-remainder) value, whichever is minimum among
them.
Below is implementation of this approach
C++
578
Chapter 94. Minimum operations to make GCD of array a multiple of k
// of k.
#include <bits/stdc++.h>
using namespace std;
int result = 0;
return result;
}
// Driver code
int main()
{
int arr[] = { 4, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 5;
cout << MinOperation(arr, n, k);
return 0;
}
Java
579
Chapter 94. Minimum operations to make GCD of array a multiple of k
// of array a mutiple of k.
import java.io.*;
class GFG
{
static int MinOperation(int a[],
int n, int k)
{
int result = 0;
return result;
}
// Driver code
public static void main (String[] args)
{
int arr[] = {4, 5, 6};
int n = arr.length;
580
Chapter 94. Minimum operations to make GCD of array a multiple of k
int k = 5;
System.out.println(MinOperation(arr, n, k));
}
}
PHP
<?php
// PHP program to make
// GCD of array a mutiple
// of k.
// If array value is
// not 1 and it is
// greater than k then
// we can increase the
// or decrease the remainder
// obtained by dividing
// k from the ith value of
// array so that we get the
// number which is either
// closer to k or its multiple
if ($a[$i] != 1 && $a[$i] > $k)
{
$result = $result + min($a[$i] %
$k, $k -
$a[$i] % $k);
}
else
{
581
Chapter 94. Minimum operations to make GCD of array a multiple of k
return $result;
}
// Driver code
$arr = array(4, 5, 6);
$n = sizeof($arr) /
sizeof($arr[0]);
$k = 5;
echo MinOperation($arr, $n, $k);
Output:
Improved By : jit_t
Source
https://www.geeksforgeeks.org/minimum-operations-make-gcd-array-multiple-k/
582
Chapter 95
Input : a[] = { 0, 0, 0 }
Output : 0
A simple solution is to generate all subsets, find product of every subset and return maximum
product.
A better solution is to use the below facts.
1. If there are even number of negative numbers and no zeros, the result is the product
of all except the largest valued negative number.
2. If there are an odd number of negative numbers and no zeros, the result is simply the
product of all.
583
Chapter 95. Minimum product subset of an array
3. If there are zeros and positive, no negative, the result is 0. The exceptional case
is when there is no negative number and all other elements positive then our result
should be the first minimum positive number.
C++
// If number is 0, we don't
// multiply it with product.
if (a[i] == 0) {
count_zero++;
continue;
}
584
Chapter 95. Minimum product subset of an array
return prod;
}
int main()
{
int a[] = { -1, -1, -2, 4, 3 };
int n = sizeof(a) / sizeof(a[0]);
cout << minProductSubset(a, n);
return 0;
}
Java
585
Chapter 95. Minimum product subset of an array
// if number is zero,count it
// but dont multiply
if(a[i] == 0){
count_zero++;
continue;
}
product *= a[i];
}
586
Chapter 95. Minimum product subset of an array
return product;
}
// main function
public static void main(String[] args)
{
System.out.println(minProductSubset(a, n));
}
}
Python3
# If number is 0, we don't
# multiply it with product.
if (a[i] == 0) :
count_zero = count_zero + 1
continue
587
Chapter 95. Minimum product subset of an array
return prod;
# Driver code
a = [ -1, -1, -2, 4, 3 ]
n = len(a)
print (minProductSubset(a, n))
# This code is contributed by
# Manish Shaw (manishshaw1)
C#
588
Chapter 95. Minimum product subset of an array
product *= a[i];
}
589
Chapter 95. Minimum product subset of an array
return product;
}
// main function
public static void Main()
{
Console.WriteLine(minProductSubset(a, n));
}
}
PHP
<?php
// PHP program to find maximum
// product of a subset.
if ($n == 1)
590
Chapter 95. Minimum product subset of an array
return $a[0];
// If number is 0, we don't
// multiply it with product.
if ($a[$i] == 0)
{
$count_zero++;
continue;
}
591
Chapter 95. Minimum product subset of an array
if ($count_neg == 0)
return $min_pos;
return $prod;
}
// Driver code
$a = array( -1, -1, -2, 4, 3 );
$n = sizeof($a);
echo(minProductSubset($a, $n));
Output:
-24
Source
https://www.geeksforgeeks.org/minimum-product-subset-array/
592
Chapter 96
Approach used: Here we traverse through each character of strings we have and while
traversing maintaining a count of the number of 1’s at each position of the strings and hence
we know the number of coinciding classes at each particular time slot. Then we just need
to find the maximum number of coinciding classes amongst all time slots.
CPP
593
Chapter 96. Minimum rooms for m events of n batches with given schedule
// Driver Code
int main()
{
int n = 3, m = 7;
string slots[n] = { "0101011",
"0011001",
"0110111" };
cout << findMinRooms(slots, n, m);
return 0;
}
Java
594
Chapter 96. Minimum rooms for m events of n batches with given schedule
return max;
}
// Driver Code
public static void main(String args[])
{
int n = 3, m = 7;
String slots[] = { "0101011",
"0011001",
"0110111" };
System.out.println( findMinRooms(slots, n, m));
}
}
C#
595
Chapter 96. Minimum rooms for m events of n batches with given schedule
return max;
}
// Driver Code
public static void Main()
{
int n = 3, m = 7;
String []slots = { "0101011",
"0011001",
"0110111" };
Console.Write( findMinRooms(slots, n, m));
}
}
Output:
596
Chapter 96. Minimum rooms for m events of n batches with given schedule
Source
https://www.geeksforgeeks.org/minimum-rooms-for-m-events-of-n-batches-with-given-schedule/
597
Chapter 97
Examples:
598
Chapter 97. Minimum rotations to unlock a circular lock
For a single ring we can rotate it in any of two direction forward or backward as:
• 0->1->2….->9->0
• 9->8->….0->9
But we are concerned with minimum number of rotation required so we should choose
min (abs(a-b), 10-abs(a-b)) as a-b denotes the number of forward rotation and 10-abs(a-b)
denotes the number of backward rotation for a ring to rotate from a to b. Further we have
to find minimum number for each ring that is for each digit. So starting from right most
digit we can easily the find minimum number of rotation required for each ring and end up
at left most digit.
C++
599
Chapter 97. Minimum rotations to unlock a circular lock
return rotation;
}
// driver code
int main()
{
int input = 28756;
int unlock_code = 98234;
cout << "Minimum Rotation = "
<< minRotation(input, unlock_code);
return 0;
}
Java
return rotation;
}
// driver code
600
Chapter 97. Minimum rotations to unlock a circular lock
C#
class GFG {
return rotation;
}
601
Chapter 97. Minimum rotations to unlock a circular lock
// Driver Code
public static void Main ()
{
int input = 28756;
int unlock_code = 98234;
Console.Write("Minimum Rotation = "+
minRotation(input, unlock_code));
}
}
PHP
<?php
// PHP program for min
// rotation to unlock
return $rotation;
}
602
Chapter 97. Minimum rotations to unlock a circular lock
// Driver Code
$input = 28756;
$unlock_code = 98234;
echo "Minimum Rotation = "
, minRotation($input, $unlock_code);
Output:
Minimum Rotation = 12
Source
https://www.geeksforgeeks.org/minimum-rotations-unlock-circular-lock/
603
Chapter 98
There is an easy trick to solve this question and that is always choose the smallest element
of array A[] and its adjacent, delete the adjacent element and copy smallest one to array B[].
Again for next iteration we have same smallest element and any random adjacent element
which is to be deleted. After n-1 operations all of elements of A[] got deleted except the
smallest one and at the same time array B[] contains “n-1” elements and all are equal to
smallest element of array A[].
Thus total sum of array B[] is equal to smallest * (n-1).
C++
604
Chapter 98. Minimum sum by choosing minimum of pairs from array
// driver function
int main()
{
int A[] = { 3, 6, 2, 8, 7, 5};
int n = sizeof(A)/ sizeof (A[0]);
cout << minSum(A, n);
return 0;
}
Python
# driver code
A = [7, 2, 3, 4, 5, 6]
print (minSum(A))
C#
605
Chapter 98. Minimum sum by choosing minimum of pairs from array
// Driver Code
static public void Main()
{
int []A = {3, 6, 2, 8, 7, 5};
int n = A.Length;
Console.WriteLine(minSum(A, n));
}
}
PHP
<?php
// PHP program to minimize the
// cost of array minimization
// Driver Code
$A = array(3, 6, 2, 8, 7, 5);
$n = count($A);
echo minSum($A, $n);
Output:
10
606
Chapter 98. Minimum sum by choosing minimum of pairs from array
Source
https://www.geeksforgeeks.org/minimum-sum-choosing-minimum-pairs-array/
607
Chapter 99
Input : n = 4
a[] = {4, 1, 8, 7}
b[] = {2, 3, 6, 5}
Output : 6
The solution to the problem is a simple greedy approach. It consists of two steps.
Step 1 : Sort both the arrays in O (n log n) time.
Step 2 : Find absolute difference of each pair of corresponding elements (elements at
same index) of both arrays and add the result to the sum S. The time complexity of this
step is O(n).
Hence, the overall time complexity of the program is O(n log n).
C++
608
Chapter 99. Minimum sum of absolute difference of pairs of two arrays
return sum;
}
// Driver code
int main()
{
// Both a[] and b[] must be of same size.
long long int a[] = {4, 1, 8, 7};
long long int b[] = {2, 3, 6, 5};
int n = sizeof(a)/sizeof(a[0]);
printf("%lld\n", findMinSum(a, b, n));
return 0;
}
Java
class MinSum
{
// Returns minimum possible pairwise
// absolute difference of two arrays.
static long findMinSum(long a[], long b[], long n)
{
// Sort both arrays
Arrays.sort(a);
Arrays.sort(b);
609
Chapter 99. Minimum sum of absolute difference of pairs of two arrays
return sum;
}
// Driver code
public static void main(String[] args)
{
// Both a[] and b[] must be of same size.
long a[] = {4, 1, 8, 7};
long b[] = {2, 3, 6, 5};
int n = a.length;
System.out.println(findMinSum(a, b, n));
}
}
Python3
for i in range(n):
sum = sum + abs(a[i] - b[i])
return sum
# Driver program
print(findMinSum(a, b, n))
610
Chapter 99. Minimum sum of absolute difference of pairs of two arrays
C#
class MinSum {
return sum;
}
// Driver code
public static void Main(String[] args)
{
// Both a[] and b[] must be of same size.
long []a = {4, 1, 8, 7};
long []b = {2, 3, 6, 5};
int n = a.Length;
Console.Write(findMinSum(a, b, n));
}
}
PHP
<?php
// PHP program to find minimum sum
// of absolute differences of two
// arrays.
611
Chapter 99. Minimum sum of absolute difference of pairs of two arrays
return $sum;
}
// Driver Code
// Both a[] and b[] must
// be of same size.
$a = array(4, 1, 8, 7);
$b = array(2, 3, 6, 5);
$n = sizeof($a);
echo(findMinSum($a, $b, $n));
Output :
Source
https://www.geeksforgeeks.org/minimum-sum-absolute-difference-pairs-two-arrays/
612
Chapter 100
613
Chapter 100. Minimum sum of product of two arrays
Since we need to minimize the product sum, we find the maximum product and reduce
it. By taking some examples, we observe that making 2*k changes to only one element is
enough to get the minimum sum. Based on this observation, we consider every element as
the element on which we apply all k operations and keep track of the element that reduces
result to minimum.
C++
614
Chapter 100. Minimum sum of product of two arrays
// product.
else if (pro > 0 && a[i] < 0)
temp = (a[i] + 2 * k) * b[i];
else if (pro > 0 && a[i] > 0)
temp = (a[i] - 2 * k) * b[i];
// Driver function
int main()
{
int a[] = { 2, 3, 4, 5, 4 };
int b[] = { 3, 4, 2, 3, 2 };
int n = 5, k = 3;
cout << minproduct(a, b, n, k)
<< endl;
return 0;
}
Java
class GFG {
615
Chapter 100. Minimum sum of product of two arrays
// Driver function
public static void main(String[] args)
{
int a[] = { 2, 3, 4, 5, 4 };
int b[] = { 3, 4, 2, 3, 2 };
int n = 5, k = 3;
System.out.println(minproduct(a, b, n, k));
}
}
Python3
616
Chapter 100. Minimum sum of product of two arrays
# operations allowed on
# first array.
diff = 0
res = 0
for i in range(n):
if (d > diff):
diff = d
return res - diff
# Driver function
a = [ 2, 3, 4, 5, 4 ]
b = [ 3, 4, 2, 3, 2 ]
617
Chapter 100. Minimum sum of product of two arrays
n = 5
k = 3
print(minproduct(a, b, n, k))
C#
class GFG {
618
Chapter 100. Minimum sum of product of two arrays
// Driver function
public static void Main()
{
int []a = { 2, 3, 4, 5, 4 };
int []b = { 3, 4, 2, 3, 2 };
int n = 5, k = 3;
Console.WriteLine(minproduct(a, b, n, k));
}
}
PHP
<?php
// PHP program to find minimum sum of product
// of two arrays with k operations allowed on
// first array.
619
Chapter 100. Minimum sum of product of two arrays
// Driver Code
$a = array(2, 3, 4, 5, 4 ,0);
$b =array(3, 4, 2, 3, 2);
$n = 5;
$k = 3;
echo minproduct($a, $b, $n, $k);
Output :
25
Improved By : vt_m
620
Chapter 100. Minimum sum of product of two arrays
Source
https://www.geeksforgeeks.org/minimum-sum-product-two-arrays/
621
Chapter 101
Input: [6, 8, 4, 5, 2, 3]
Output: 604
The minimum sum is formed by numbers
358 and 246
Input: [5, 3, 0, 7, 4]
Output: 82
The minimum sum is formed by numbers
35 and 047
Since we want to minimize the sum of two numbers to be formed, we must divide all digits
in two halves and assign half-half digits to them. We also need to make sure that the leading
digits are smaller.
We build a Min Heap with the elements of the given array, which takes O(n) worst time.
Now we retrieve min values (2 at a time) of array, by polling from the Priority Queue and
append these two min values to our numbers, till the heap becomes empty, i.e., all the
elements of array get exhausted. We return the sum of two formed numbers, which is our
required answer.
C/C++
622
Chapter 101. Minimum sum of two numbers formed from digits of an array
int main()
{
int arr[] = {6, 8, 4, 5, 2, 3};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<minSum(arr, n)<<endl;
return 0;
}
// Contributed By: Harshit Sidhwa
623
Chapter 101. Minimum sum of two numbers formed from digits of an array
Java
class MinSum
{
// Returns sum of two numbers formed
// from all digits in a[]
public static long solve(int[] a)
{
// min Heap
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
return sum;
}
// Driver code
public static void main (String[] args)
{
int arr[] = {6, 8, 4, 5, 2, 3};
System.out.println("The required sum is "+ solve(arr));
}
}
Output:
624
Chapter 101. Minimum sum of two numbers formed from digits of an array
Source
https://www.geeksforgeeks.org/minimum-sum-two-numbers-formed-digits-array-2/
625
Chapter 102
Note: Output is printed after rounding off the value as in the 2nd example, the output will
be around 3.76 approx.
Approach:
It is given that maximum no. of chocolates are selected so consider total pile since it will
be maximum.
Next, it is given that in the each iteration only square of chocolates are left so that by
considering the mathematics equation of
Since here k times the square root is performed so the (1/2)k is powered with the N.
Consider the example of 100000000 chocolates and no. of iterations is 3 then it will be as
626
Chapter 102. Number of chocolates left after k iterations
(((100000000)1/2)1/2)1/2 = (100000000)(1/2)3 = 10
C++
// Driver code
int main()
{
int k = 3, n = 100000000;
return 0;
}
Java
class GFG
{
// Function to find the
// chocolates left
static int results(int n, int k)
{
627
Chapter 102. Number of chocolates left after k iterations
return (int)Math.round(Math.pow(n,
(1.0 / Math.pow(2.0, k))));
}
// Driver code
public static void main(String args[])
{
int k = 3, n = 100000000;
C#
class GFG
{
// Function to find the
// chocolates left
static int results(int n, int k)
{
return (int)Math.Round(Math.Pow(n,
(1.0 / Math.Pow(2.0, k))));
}
// Driver code
public static void Main()
{
int k = 3, n = 100000000;
Python
628
Chapter 102. Number of chocolates left after k iterations
# Driver code
k = 3
n = 100000000
PHP
<?php
// PHP program to find remaining
// chocolates after k iterations
// Function to find
// the chocolates left
function results($n, $k)
{
return round(pow($n, (1.0 /
pow(2, $k))));
}
// Driver code
$k = 3;
$n = 100000000;
echo ("Chocolates left after ");
echo ($k);
629
Chapter 102. Number of chocolates left after k iterations
?>
Output:
Source
https://www.geeksforgeeks.org/number-of-chocolates-left-after-k-iterations/
630
Chapter 103
Input: V = 15, E = 14
1 10 // edge 1
1 5 // edge 2
5 10 // edge 3
2 9 // ..
9 15 // ..
2 15 // ..
2 12 // ..
12 15 // ..
13 8 // ..
6 14 // ..
14 3 // ..
3 7 // ..
7 11 // edge 13
11 6 // edge 14
631
Chapter 103. Number of single cycle components in an undirected graph
Output :2
In the above-mentioned example, the two
single-cyclic-components are composed of
vertices (1, 10, 5) and (6, 11, 7, 3, 14)
respectively.
Now we can easily see that a single-cycle-component is a connected component where every
vertex has the degree as two.
Therefore, in order to solve this problem we first identify all the connected components
of the disconnected graph. For this, we use depth-first search algorithm. For the DFS
algorithm to work, it is required to maintain an array ‘found’ to keep an account of all the
vertices that have been discovered by the recursive function DFS. Once all the elements of a
particular connected component are discovered (like vertices(9, 2, 15, 12) form a connected
graph component ), we check if all the vertices in the component are having the degree
equal to two. If yes, we increase the counter variable ‘count’ which denotes the number of
single-cycle-components found in the given graph. To keep an account of the component we
are presently dealing with, we may use a vector array ‘curr_graph’ as well.
// adjacency list
vector<int> adj_list[N];
632
Chapter 103. Number of single cycle components in an undirected graph
DFS(it);
}
int main()
{
// n->number of vertices
// m->number of edges
int n = 15, m = 14;
633
Chapter 103. Number of single cycle components in an undirected graph
addEdge(adj_list, 1, 10);
addEdge(adj_list, 1, 5);
addEdge(adj_list, 5, 10);
addEdge(adj_list, 2, 9);
addEdge(adj_list, 9, 15);
addEdge(adj_list, 2, 15);
addEdge(adj_list, 2, 12);
addEdge(adj_list, 12, 15);
addEdge(adj_list, 13, 8);
addEdge(adj_list, 6, 14);
addEdge(adj_list, 14, 3);
addEdge(adj_list, 3, 7);
addEdge(adj_list, 7, 11);
addEdge(adj_list, 11, 6);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/number-of-simple-cyclic-components-in-an-undirected-graph/
634
Chapter 104
Operating System Program for Next Fit algorithm in Memory Management - GeeksforGeeks
Prerequisite: Partition allocation methods
What is Next Fit ?
Next fit is a modified version of ‘first fit’. It begins as first fit to find a free partition but
when called next time it starts searching from where it left off, not from the beginning. This
policy makes use of a roving pointer. The pointer roves along the memory chain to search
for a next fit. This helps in, to avoid the usage of memory always from the head (beginning)
of the free block chain.
What are its advantage over first fit ?
• First fit is a straight and fast algorithm, but tends to cut large portion of free parts
into small pieces due to which, processes that needs large portion of memory block
would not get anything even if the sum of all small pieces is greater than it required
which is so called external fragmentation problem.
• Another problem of first fit is that it tends to allocate memory parts at the begining
of the memory, which may leads to more internal fragements at the begining. Next fit
tries to address this problem by starting search for the free portion of parts not from
the start of the memory, but from where it ends last time.
• Next fit is a very fast searching algorithm and is also comparatively faster than First
Fit and Best Fit Memory Management Algorithms.
Example:
Input : blockSize[] = {5, 10, 20};
635
Chapter 104. Operating System Program for Next Fit algorithm in Memory Management
Algorithm:
1. Input the number of memory blocks and their sizes and initializes all the blocks as
free.
636
Chapter 104. Operating System Program for Next Fit algorithm in Memory Management
637
Chapter 104. Operating System Program for Next Fit algorithm in Memory Management
break;
}
// Driver program
int main()
{
int blockSize[] = { 5, 10, 20 };
int processSize[] = { 10, 20, 5 };
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);
638
Chapter 104. Operating System Program for Next Fit algorithm in Memory Management
return 0;
}
Output:
Improved By : ishita_thakkar
Source
https://www.geeksforgeeks.org/program-next-fit-algorithm-memory-management/
639
Chapter 105
Given programs stored on a computer tape and length of each program is where
, find the order in which the programs should be stored in the
Input : n = 3
L[] = { 5, 3, 10 }
Output : Order should be { 3, 5, 10 } with MRT = 29/3
640
Chapter 105. Optimal Storage on Tapes
The sequential access of data in a tape has some limitations. Order must be defined in
which the data/programs in a tape are stored so that least MRT can be obtained. Hence
the order of storing becomes very important to reduce the data retrieval/access time.
Thus, the task gets reduced – to define the correct order and hence minimize the MRT, i.e.
It’s clear that by following the second order in storing the programs, the mean retrieval time
is least.
In above example, the first program’s length is added ‘n’ times, the second ‘n-1’ times…and
so on till the last program is added only once. So, careful analysis suggests that in order to
minimize the MRT, programs having greater lengths should be put towards the end so that
the summation is reduced. Or, the lengths of the programs should be sorted in increasing
order. That’s the Greedy Algorithm in use – at each step we make the immediate choice of
putting the program having the least time first, in order to build up the ultimate optimized
solution to the problem piece by piece.
Below is the implementation:
C++
641
Chapter 105. Optimal Storage on Tapes
Java
class GFG
{
642
Chapter 105. Optimal Storage on Tapes
// Driver Code
public static void main (String[] args)
{
int []L = { 2, 5, 4 };
int n = L.length;
findOrderMRT(L, n);
}
}
643
Chapter 105. Optimal Storage on Tapes
C#
class GFG
{
// Driver Code
644
Chapter 105. Optimal Storage on Tapes
Output:
Time complexity of the above program is the time complexity for sorting, that is
Improved By : vt_m
Source
https://www.geeksforgeeks.org/optimal-storage-tapes/
645
Chapter 106
Input : N = 2
arr[] = { 5, 8, 3, 9 }
Output : (3, 9) (5, 8)
Explanation:
Possible pairs are :
1. (8, 9) (3, 5) Maximum Sum of a Pair = 17
2. (5, 9) (3, 8) Maximum Sum of a Pair = 14
3. (3, 9) (5, 8) Maximum Sum of a Pair = 13
Thus, in case 3, the maximum pair sum is minimum of all the other cases. Hence,
the answer is(3, 9) (5, 8).
Input : N = 2
arr[] = { 9, 6, 5, 1 }
Output : (1, 9) (5, 6)
Approach: The idea is to first sort the given array and then iterate over the loop to form
pairs (i, j) where i would start from 0 and j would start from end of array correspondingly.
Increment i and Decrement j to form the next pair and so on.
Below is the implementation of above approach.
C++
646
Chapter 106. Pair formation such that maximum pair sum is minimized
// Driver Code
int main()
{
int arr[] = { 9, 6, 5, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
findOptimalPairs(arr, N);
return 0;
}
Java
class GFG {
647
Chapter 106. Pair formation such that maximum pair sum is minimized
// Driver Code
public static void main (String[] args)
{
int arr[] = {9, 6, 5, 1};
int N = arr.length;
findOptimalPairs(arr, N);
}
}
Output:
(1, 9) (5, 6)
Improved By : vt_m
Source
https://www.geeksforgeeks.org/pair-formation-maximum-pair-sum-minimized/
648
Chapter 107
Input : 13 x 29
Output : 9
Explanation :
2 (squares of size 13x13) +
4 (squares of size 3x3) +
3 (squares of size 1x1)=9
Input : 4 x 5
Output : 5
Explanation :
1 (squares of size 4x4) +
4 (squares of size 1x1)
We know that if we want to cut minimum number of squares from the paper then we would
have to cut largest square possible from the paper first and largest square will have same
side as smaller side of the paper. For example if paper have the size 13 x 29, then maximum
square will be of side 13. so we can cut 2 square of size 13 x 13 (29/13 = 2). Now remaining
paper will have size 3 x 13. Similarly we can cut remaining paper by using 4 squares of size
3 x 3 and 3 squares of 1 x 1. So minimum 9 squares can be cut from the Paper of size 13 x
29.
649
Chapter 107. Paper Cut into Minimum Number of Squares
650
Chapter 107. Paper Cut into Minimum Number of Squares
return result;
}
// Driver code
int main()
{
int n = 13, m = 29;
cout << minimumSquare(n, m);
return 0;
}
Java
return result;
651
Chapter 107. Paper Cut into Minimum Number of Squares
// Driver code
public static void main(String[] args)
{
int n = 13, m = 29;
System.out.println(minimumSquare(n, m));
}
}
Python3
result = 0
rem = 0
# Update result
result += int(a / b)
rem = int(a % b)
a = b
b = rem
return result
# Driver code
n = 13
m = 29
print(minimumSquare(n, m))
652
Chapter 107. Paper Cut into Minimum Number of Squares
Output:
Note that the above Greedy solution doesn’t always produce optimal result. For
example if input is 36 x 30, the above algorithm would produce output 6, but we can cut
the paper in 5 squares
1) Three squares of size 12 x 12
2) Two squares of size 18 x 18.
Thanks to Sergey V. Pereslavtsev for pointing out the above case.
Source
https://www.geeksforgeeks.org/paper-cut-minimum-number-squares/
653
Chapter 108
Partition into two subarrays of lengths k and (N - k) such that the difference of sums is
maximum - GeeksforGeeks
Given an array of non-negative integers of length N and an integer k. Partition the given
array into two subarrays of length K and N – k so that the difference between the sum of
both subarray is maximum.
Examples :
654
Chapter 108. Partition into two subarrays of lengths k and (N – k) such that the
difference of sums is maximum
Choose k numbers with largest possible sum. Then the solution obviously is k largest
numbers. So that here greedy algorithm works – at each step we choose the largest possible
number until we get all K numbers.
In this problem we should divide the array of N numbers into two subarrays of k and N – k
numbers respectively. Consider two cases –
• The subarray with largest sum, among these two subarrays, is subarray of K numbers.
Then we want to maximize the sum in it, since the sum in the second subarray will only
decrease if the sum in the first subarray will increase. So we are now in sub-problem
considered above and should choose k largest numbers.
• The subarray with largest sum, among these two subarray, is subarray of N – k num-
bers. Similarly to the previous case we then have to choose N – k largest numbers
among all numbers.
Now, Let’s think which of the two above cases actually gives the answer. We can easily
see that larger difference would be when more numbers are included to the group of largest
numbers. Hence we could set M = max(k, N – k), find the sum of M largest numbers (let
it be S1) and then the answer is S1 – (S – S1), where S is the sum of all numbers.
Below is the implementation of the above approach :
C++
// Calculating max_difference
max_difference = S1 - (S - S1);
return max_difference;
}
655
Chapter 108. Partition into two subarrays of lengths k and (N – k) such that the
difference of sums is maximum
// Driver function
int main()
{
int arr[] = { 8, 4, 5, 2, 10 };
int N = sizeof(arr) / sizeof(arr[0]);
int k = 2;
cout << maxDifference(arr, N, k) << endl;
return 0;
}
Python3
# Calculating max_difference
max_difference = S1 - (S - S1)
return max_difference
# Driver Code
arr = [ 8, 4, 5, 2, 10 ]
N = len(arr)
k = 2
print(maxDifference(arr, N, k))
PHP
<?php
656
Chapter 108. Partition into two subarrays of lengths k and (N – k) such that the
difference of sums is maximum
// Function to calculate
// max_difference
function maxDifference($arr, $N, $k)
{
$M; $S = 0; $S1 = 0;
$max_difference = 0;
// Calculating
// max_difference
$max_difference = $S1 - ($S - $S1);
return $max_difference;
}
// Driver Code
$arr = array(8, 4, 5, 2, 10);
$N = count($arr);
$k = 2;
echo maxDifference($arr, $N, $k);
Output :
17
Further Optimizations : We can use Heap (or priority queue) to find M largest elements
efficiently. Refer k largest(or smallest) elements in an array for details.
Improved By : vt_m
657
Chapter 108. Partition into two subarrays of lengths k and (N – k) such that the
difference of sums is maximum
Source
https://www.geeksforgeeks.org/partition-into-two-subarrays-of-lengths-k-and-n-k-such-that-the-difference-of-sums
658
Chapter 109
Place N^2 numbers in matrix such that every row has an equal sum - GeeksforGeeks
Given a number N, place numbers from the range [1, N2 ] in an NxN matrix such that sum
in every row is equal.
Examples:
Input: N = 3
Output: 1 5 9
2 6 7
3 4 8
Sum in 1st row: 15
Sum in 2nd row: 15
Sum in 2nd row: 15
Input: N = 5
Output: 1 7 13 19 25
2 8 14 20 21
3 9 15 16 22
4 10 11 17 23
5 6 12 18 24
A Greedy Approach has been used to fill the matrix, where the insertion of elements in
the matrix is done row-wise. The required matrix can be obtained using below steps:
• Fill the matrix initially with numbers in the range [1, N2 ] using matrix traversal.
659
Chapter 109. Place N^2 numbers in matrix such that every row has an equal sum
• Traverse the matrix and change every position in a new matrix considering it as answer
matrix by answer[i][j] = mat[j][(i+j)%n].
// Driver Code
public static void main(String[] args)
{
int n = 5;
660
Chapter 109. Place N^2 numbers in matrix such that every row has an equal sum
Output:
1 7 13 19 25
2 8 14 20 21
3 9 15 16 22
4 10 11 17 23
5 6 12 18 24
Source
https://www.geeksforgeeks.org/place-n2-numbers-in-matrix-such-that-every-row-has-an-equal-sum/
661
Chapter 110
A brute force approach would be to check all feasible sets of combinations of police and
thief and return the maximum size set among them. Its time complexity is exponential and
it can be optimized if we observe an important property.
662
Chapter 110. Policemen catch thieves
663
Chapter 110. Policemen catch thieves
// can be caught
if (abs(thi[l] - pol[r]) <= k) {
res++;
l++;
r++;
}
return res;
}
// Driver program
int main()
{
int k, n;
return 0;
}
Java
664
Chapter 110. Policemen catch thieves
import java.io.*;
class GFG
{
// Returns maximum number of thieves
// that can be caught.
static int policeThief(char arr[], int n, int k)
{
int res = 0;
ArrayList<Integer> thi = new ArrayList<Integer>();
ArrayList<Integer> pol = new ArrayList<Integer>();
// can be caught
if (Math.abs(thi.get(l) - pol.get(r)) <= k) {
res++;
l++;
r++;
}
// Driver program
public static void main(String args[])
{
int k, n;
char arr1[] =new char[] { 'P', 'T', 'T',
'P', 'T' };
k = 2;
665
Chapter 110. Policemen catch thieves
n = arr1.length;
System.out.println("Maximum thieves caught: "
+policeThief(arr1, n, k));
Output:
The time complexity of the above approach in O(N) where N is the size of the array.
Source
https://www.geeksforgeeks.org/policemen-catch-thieves/
666
Chapter 111
• It is a lossless data compressing technique generating variable length codes for different
symbols.
• It is based on greedy approach which considers frequency/probability of alphabets for
generating codes.
667
Chapter 111. Practice Questions on Huffman Encoding
Que – 2. How many bits may be required for encoding the message ‘mississippi’?
Solution: Following is the frequency table of characters in ‘mississippi’ in non-decreasing
order of frequency:
668
Chapter 111. Practice Questions on Huffman Encoding
• Generate codes for each character using Huffman tree (if not given)
• Using prefix matching, replace the codes with characters.
Que – 3. The characters a to h have the set of frequencies based on the first 8 Fibonacci
numbers as follows:
669
Chapter 111. Practice Questions on Huffman Encoding
a : 1, b : 1, c : 2, d : 3, e : 5, f : 8, g : 13, h : 21
A Huffman code is used to represent the characters. What is the sequence of characters
corresponding to the following code?
110111100111010
(A) fdheg
(B) ecgdf
(C) dchfg
(D) fehdg
Solution: Using frequencies given in the question, huffman tree can be generated as:
670
Chapter 111. Practice Questions on Huffman Encoding
671
Chapter 111. Practice Questions on Huffman Encoding
(A) 224
(B) 800
(C) 576
(D) 324
Solutions: Finding number of bits without using Huffman,
Total number of characters = sum of frequencies = 100
size of 1 character = 1byte = 8 bits
Total number of bits = 8*100 = 800
Using Huffman Encoding, Total number of bits needed can be calculated as:
5*4 + 9*4 + 12*3 + 13*3 + 16*3 + 45* 1 = 224
Bits saved = 800-224 = 576.
672
Chapter 111. Practice Questions on Huffman Encoding
Source
https://www.geeksforgeeks.org/practice-questions-on-huffman-encoding/
673
Chapter 112
674
Chapter 112. Prim’s Algorithm (Simple Implementation for Adjacency Matrix
Representation)
if (u == v)
return false;
if (inMST[u] == false && inMST[v] == false)
return false;
else if (inMST[u] == true && inMST[v] == true)
return false;
return true;
}
675
Chapter 112. Prim’s Algorithm (Simple Implementation for Adjacency Matrix
Representation)
2 3
(0)--(1)--(2)
| / \ |
6| 8/ \5 |7
| / \ |
(3)-------(4)
9 */
int cost[][V] = {
{ INT_MAX, 2, INT_MAX, 6, INT_MAX },
{ 2, INT_MAX, 3, 8, 5 },
{ INT_MAX, 3, INT_MAX, INT_MAX, 7 },
{ 6, 8, INT_MAX, INT_MAX, 9 },
{ INT_MAX, 5, 7, 9, INT_MAX },
};
return 0;
}
Output:
Minimum cost= 16
Source
https://www.geeksforgeeks.org/prims-algorithm-simple-implementation-for-adjacency-matrix-representation/
676
Chapter 113
677
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
Initially, key value of first vertex is 0 and INF (infinite) for all other vertices. So vertex 0
is extracted from Min Heap and key values of vertices adjacent to 0 (1 and 7) are updated.
Min Heap contains all vertices except vertex 0.
The vertices in green color are the vertices included in MST.
Since key value of vertex 1 is minimum among all nodes in Min Heap, it is extracted from
Min Heap and key values of vertices adjacent to 1 are updated (Key is updated if the a
vertex is not in Min Heap and previous key value is greater than the weight of edge from 1
to the adjacent). Min Heap contains all vertices except vertex 0 and 1.
Since key value of vertex 7 is minimum among all nodes in Min Heap, it is extracted from
Min Heap and key values of vertices adjacent to 7 are updated (Key is updated if the a
vertex is not in Min Heap and previous key value is greater than the weight of edge from 7
to the adjacent). Min Heap contains all vertices except vertex 0, 1 and 7.
Since key value of vertex 6 is minimum among all nodes in Min Heap, it is extracted from
Min Heap and key values of vertices adjacent to 6 are updated (Key is updated if the a
678
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
vertex is not in Min Heap and previous key value is greater than the weight of edge from 6
to the adjacent). Min Heap contains all vertices except vertex 0, 1, 7 and 6.
The above steps are repeated for rest of the nodes in Min Heap till Min Heap becomes empty
C++
// C / C++ program for Prim's MST for adjacency list representation of graph
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
679
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
{
struct AdjListNode* newNode = (struct AdjListNode*)malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->weight = weight;
newNode->next = NULL;
return newNode;
}
return graph;
}
680
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
// A utility function to swap two nodes of min heap. Needed for min heapify
void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b)
{
struct MinHeapNode* t = *a;
*a = *b;
*b = t;
}
681
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
if (smallest != idx) {
// The nodes to be swapped in min heap
MinHeapNode* smallestNode = minHeap->array[smallest];
MinHeapNode* idxNode = minHeap->array[idx];
// Swap positions
minHeap->pos[smallestNode->v] = idx;
minHeap->pos[idxNode->v] = smallest;
// Swap nodes
swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
return root;
}
682
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
// uses pos[] of min heap to get the current index of node in min heap
void decreaseKey(struct MinHeap* minHeap, int v, int key)
{
// Get the index of v in heap array
int i = minHeap->pos[v];
683
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
684
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
PrimMST(graph);
return 0;
}
Java
// Constructor
node1(int a, int b)
{
dest = a;
weight = b;
685
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
}
}
static class Graph {
// Constructor
Graph(int e)
{
V = e;
adj = new LinkedList[V];
for (int o = 0; o < V; o++)
adj[o] = new LinkedList<>();
}
}
@Override
public int compare(node node0, node node1)
{
return node0.key - node1.key;
}
}
686
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
graph.adj[src].addLast(node0);
graph.adj[dest].addLast(node);
}
// Initialize to false
mstset[o] = false;
// PriorityQueue
PriorityQueue<node> queue = new PriorityQueue<>(graph.V, new comparator());
687
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
// If V is in PriorityQueue
if (mstset[iterator.dest] == false) {
// If the key value of the adjacent vertex is
// more than the extracted key
// update the key value of adjacent vertex
// to update first remove and add the updated vertex
if (e[iterator.dest].key > iterator.weight) {
queue.remove(e[iterator.dest]);
e[iterator.dest].key = iterator.weight;
queue.add(e[iterator.dest]);
parent[iterator.dest] = node0.vertex;
}
}
}
}
e.addEdge(graph, 0, 1, 4);
e.addEdge(graph, 0, 7, 8);
e.addEdge(graph, 1, 2, 8);
e.addEdge(graph, 1, 7, 11);
e.addEdge(graph, 2, 3, 7);
e.addEdge(graph, 2, 8, 2);
e.addEdge(graph, 2, 5, 4);
e.addEdge(graph, 3, 4, 9);
e.addEdge(graph, 3, 5, 14);
e.addEdge(graph, 4, 5, 10);
688
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
e.addEdge(graph, 5, 6, 2);
e.addEdge(graph, 6, 7, 1);
e.addEdge(graph, 6, 8, 6);
e.addEdge(graph, 7, 8, 7);
// Method invoked
e.prims_mst(graph);
}
}
// This code is contributed by Vikash Kumar Dubey
Python
class Heap():
def __init__(self):
self.array = []
self.size = 0
self.pos = []
689
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
smallest = left
# Swap positions
self.pos[ self.array[smallest][0] ] = idx
self.pos[ self.array[idx][0] ] = smallest
# Swap nodes
self.swapMinHeapNode(smallest, idx)
self.minHeapify(smallest)
return root
def isEmpty(self):
return True if self.size == 0 else False
690
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
i = self.pos[v]
class Graph():
691
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
692
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
v = pCrawl[0]
printArr(parent, V)
Output:
0 - 1
5 - 2
2 - 3
3 - 4
6 - 5
693
Chapter 113. Prim’s MST for Adjacency List Representation Greedy Algo-6
7 - 6
0 - 7
2 - 8
Time Complexity: The time complexity of the above code/algorithm looks O(V^2) as
there are two nested while loops. If we take a closer look, we can observe that the statements
in inner loop are executed O(V+E) times (similar to BFS). The inner loop has decreaseKey()
operation which takes O(LogV) time. So overall time complexity is O(E+V)*O(LogV) which
is O((E+V)*LogV) = O(ELogV) (For a connected graph, V = O(E))
References:
Introduction to Algorithms by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson,
Ronald L.
http://en.wikipedia.org/wiki/Prim’s_algorithm
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please
write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.
Improved By : VikashDubey, Sumon Nath
Source
https://www.geeksforgeeks.org/prims-mst-for-adjacency-list-representation-greedy-algo-6/
694
Chapter 114
695
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
are used only for vertices which are not yet included in MST, the key value for these vertices
indicate the minimum weight edges connecting them to the set of vertices included in MST.
Let us understand with the following example:
The set mstSet is initially empty and keys assigned to vertices are {0, INF, INF, INF, INF,
INF, INF, INF} where INF indicates infinite. Now pick the vertex with minimum key value.
The vertex 0 is picked, include it in mstSet. So mstSet becomes {0}. After including to
mstSet, update key values of adjacent vertices. Adjacent vertices of 0 are 1 and 7. The key
values of 1 and 7 are updated as 4 and 8. Following subgraph shows vertices and their key
values, only the vertices with finite key values are shown. The vertices included in MST are
shown in green color.
Pick the vertex with minimum key value and not already included in MST (not in mstSET).
The vertex 1 is picked and added to mstSet. So mstSet now becomes {0, 1}. Update the
key values of adjacent vertices of 1. The key value of vertex 2 becomes 8.
Pick the vertex with minimum key value and not already included in MST (not in mstSET).
We can either pick vertex 7 or vertex 2, let vertex 7 is picked. So mstSet now becomes {0,
1, 7}. Update the key values of adjacent vertices of 7. The key value of vertex 6 and 8
becomes finite (7 and 1 respectively).
696
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
Pick the vertex with minimum key value and not already included in MST (not in mstSET).
Vertex 6 is picked. So mstSet now becomes {0, 1, 7, 6}. Update the key values of adjacent
vertices of 6. The key value of vertex 5 and 8 are updated.
We repeat the above steps until mstSet includes all vertices of given graph. Finally, we get
the following graph.
697
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
return min_index;
}
698
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
return 0;
}
Java
699
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
import java.util.*;
import java.lang.*;
import java.io.*;
class MST
{
// Number of vertices in the graph
private static final int V=5;
return min_index;
}
700
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
701
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
Python
class Graph():
702
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
self.printMST(parent)
g = Graph(5)
g.graph = [ [0, 2, 0, 6, 0],
703
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]
g.primMST();
C#
return min_index;
}
704
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
705
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
// Driver Code
public static void Main ()
{
706
Chapter 114. Prim’s Minimum Spanning Tree (MST) Greedy Algo-5
Output:
Edge Weight
0 - 1 2
1 - 2 3
0 - 3 6
1 - 4 5
Time Complexity of the above program is O(V^2). If the input graph is represented using
adjacency list, then the time complexity of Prim’s algorithm can be reduced to O(E log V)
with the help of binary heap. Please see Prim’s MST for Adjacency List Representation for
more details.
Improved By : vt_m, AnkurKarmakar
Source
https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/
707
Chapter 115
Print a closest string that does not contain adjacent duplicates - GeeksforGeeks
Given a string S, change the smallest number of letters in S such that all adjacent characters
are different. Print the resultant string.
Examples :
Input : S = "aab"
Output: acb
Explanation :
Loop will start for i-th character, which
is second ‘a’. It’s cannot be ‘b’ since it
matches with third char. So output should
be ‘acb’.
Input : S = "geeksforgeeks"
Output: geaksforgeaks
Explanation :
Resultant string, after making minimal
changes. S = "geaksforgeaks". We made two
changes, which is the optimal solution here.
We can solve this problem using greedy approach. Let us consider a segment of length k of
consecutive identical characters. We have to make at least [K/2] changes in the segment, to
make that there are no identical characters in a row. We can also change the second, fourth
etc.. characters of the string that is it should not be equal to the letter on the left side and
the letter to the right side.
708
Chapter 115. Print a closest string that does not contain adjacent duplicates
Traverse the string from starting index (i = 1) and if any two adjacent letters( i & i-1) are
equal then initialize (i)th character with ‘a’ and start another loop to make (i)th character
different from the left and right letters.
Below is the implementation of above approach :
C++
i++;
}
}
return s;
}
// Driver Function
int main()
{
string s = "geeksforgeeks";
cout << noAdjacentDup(s);
return 0;
}
Java
709
Chapter 115. Print a closest string that does not contain adjacent duplicates
i++;
}
}
return (new String(s));
}
// Driver function
public static void main(String argc[]){
String s = "geeksforgeeks";
System.out.println(noAdjacentDup(s));
Python3
710
Chapter 115. Print a closest string that does not contain adjacent duplicates
n = len(s)
for i in range(1, n):
i += 1
return s
# Driver Function
s = list("geeksforgeeks")
print("".join(noAdjacentDup(s)))
C#
class GfG{
char[] s = s1.ToCharArray();
for (int i = 1; i < n; i++)
{
// If any two adjacent
711
Chapter 115. Print a closest string that does not contain adjacent duplicates
i++;
}
}
return (new String(s));
}
// Driver function
public static void Main(String[] argc)
{
String s = "geeksforgeeks";
// Function calling
Console.Write(noAdjacentDup(s));
}
}
PHP
<?php
// PHP program to print a
// string with no adjacent
// duplicates by doing minimum
// changes to original string
// Function to print
// simple string
function noAdjacentDup($s)
{
$n = strlen($s);
for ($i = 1; $i < $n; $i++)
{
// If any two adjacent
// characters are equal
712
Chapter 115. Print a closest string that does not contain adjacent duplicates
$i++;
}
}
return $s;
}
// Driver Code
$s = "geeksforgeeks";
echo (noAdjacentDup($s));
Output :
geaksforgeaks
Source
https://www.geeksforgeeks.org/print-a-closest-string-that-does-not-contain-adjacent-duplicates/
713
Chapter 116
Problem Solving for Minimum Spanning Trees (Kruskal’s and Prim’s) - GeeksforGeeks
Minimum spanning Tree (MST) is an important topic for GATE. Therefore, we will discuss
how to solve different types of questions based on MST. Before understanding this article,
you should understand basics of MST and their algorithms (Kruskal’s algorithm and Prim’s
algorithm).
Type 1. Conceptual questions based on MST –
There are some important properties of MST on the basis of which conceptual questions
can be asked as:
Que – 1. Let G be an undirected connected graph with distinct edge weight. Let emax
be the edge with maximum weight and emin the edge with minimum weight. Which of the
following statements is false? (GATE CS 2000)
714
Chapter 116. Problem Solving for Minimum Spanning Trees (Kruskal’s and Prim’s)
Que – 2. Consider a complete undirected graph with vertex set {0, 1, 2, 3, 4}. Entry Wij
in the matrix W below is the weight of the edge {i, j}. What is the minimum possible weight
of a spanning tree T in this graph such that vertex 1 is a leaf node in the tree T? (GATE
CS 2010)
(A) 7
(B) 8
(C) 9
(D) 10
Solution: In the adjacency matrix of the graph with 5 vertices (v1 to v5), the edges
arranged in non-decreasing order are:
715
Chapter 116. Problem Solving for Minimum Spanning Trees (Kruskal’s and Prim’s)
As it is given, vertex v1 is a leaf node, it should have only one edge incident to it. Therefore,
we will consider it in the end. Considering vertices v2 to v5, edges in non decreasing order
are:
Adding first three edges (v4,v5), (v3,v5), (v2,v4), no cycle is created. Also, we can connect
v1 to v2 using edge (v1,v2). The total weight is sum of weight of these 4 edges which is 10.
Type 3. How many minimum spanning trees are possible using Kruskal’s algo-
rithm for a given graph –
Que – 3. The number of distinct minimum spanning trees for the weighted graph below
is ____ (GATE-CS-2014)
(A) 4
(B) 5
(C) 6
(D) 7
Solution: There are 5 edges with weight 1 and adding them all in MST does not create
cycle.
As the graph has 9 vertices, therefore we require total 8 edges out of which 5 has been added.
Out of remaining 3, one edge is fixed represented by f.
For remaining 2 edges, one is to be chosen from c or d or e and another one is to be chosen
from a or b. Remaining black ones will always create cycle so they are not considered. So,
possible MST are 3*2 = 6.
716
Chapter 116. Problem Solving for Minimum Spanning Trees (Kruskal’s and Prim’s)
Type 4. Out of given sequences, which one is not the sequence of edges added
to the MST using Kruskal’s algorithm –
To solve this type of questions, try to find out the sequence of edges which can be produced
by Kruskal. The sequence which does not match will be the answer.
Que – 4. Consider the following graph:
Which one of the following is NOT the sequence of edges added to the minimum spanning
tree using Kruskal’s algorithm? (GATE-CS-2009)
(A) (b,e), (e,f), (a,c), (b,c), (f,g), (c,d)
(B) (b,e), (e,f), (a,c), (f,g), (b,c), (c,d)
(C) (b,e), (a,c), (e,f), (b,c), (f,g), (c,d)
(D) (b,e), (e,f), (b,c), (a,c), (f,g), (c,d)
Solution: Kruskal algorithms adds the edges in non-decreasing order of their weights,
therefore, we first sort the edges in non-decreasing order of weight as:
(b,e), (e,f), (a,c), (b,c), (f,g), (a,b), (e,g), (c,d), (b,d), (e,d), (d,f).
717
Chapter 116. Problem Solving for Minimum Spanning Trees (Kruskal’s and Prim’s)
First it will add (b,e) in MST. Then, it will add (e,f) as well as (a,c) (either (e,f) followed
by (a,c) or vice versa) because of both having same weight and adding both of them will
not create cycle.
However, in option (D), (b,c) has been added to MST before adding (a,c). So it can’t be
the sequence produced by Kruskal’s algorithm.
Source
https://www.geeksforgeeks.org/problem-solving-minimum-spanning-trees-kruskals-prims/
718
Chapter 117
719
Chapter 117. Program for Best Fit algorithm in Memory Management
Implementation:
1- Input memory blocks and processes with sizes.
2- Initialize all memory blocks as free.
3- Start by picking each process and find the
minimum block size that can be assigned to
current process i.e., find min(bockSize[1],
blockSize[2],.....blockSize[n]) >
processSize[current], if found then assign
it to the current process.
5- If not then leave that process and keep checking
the further processes.
Below is implementation.
C/C++
720
Chapter 117. Program for Best Fit algorithm in Memory Management
{
// Stores block id of the block allocated to a
// process
int allocation[n];
721
Chapter 117. Program for Best Fit algorithm in Memory Management
// Driver code
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize)/sizeof(blockSize[0]);
int n = sizeof(processSize)/sizeof(processSize[0]);
return 0 ;
}
Java
722
Chapter 117. Program for Best Fit algorithm in Memory Management
// Driver Method
public static void main(String[] args)
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = blockSize.length;
int n = processSize.length;
C#
723
Chapter 117. Program for Best Fit algorithm in Memory Management
Console.WriteLine("\nProcess No.\tProcess"
724
Chapter 117. Program for Best Fit algorithm in Memory Management
if (allocation[i] != -1)
Console.Write(allocation[i] + 1);
else
Console.Write("Not Allocated");
Console.WriteLine();
}
}
// Driver Method
public static void Main()
{
int []blockSize = {100, 500, 200, 300, 600};
int []processSize = {212, 417, 112, 426};
int m = blockSize.Length;
int n = processSize.Length;
Output:
725
Chapter 117. Program for Best Fit algorithm in Memory Management
Best Fit:
300K is allocated from block of size 350K. 50 is left in the block.
25K is allocated from the remaining 50K block. 25K is left in the block.
125K is allocated from 150 K block. 25K is left in this block also.
50K can’t be allocated even if there is 25K + 25K space available.
First Fit:
300K request is allocated from 350K block, 50K is left out.
25K is be allocated from 150K block, 125K is left out.
Then 125K and 50K are allocated to remaining left out partitions.
So, first fit can handle requests.
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/program-best-fit-algorithm-memory-management/
726
Chapter 118
• Its advantage is that it is the fastest search as it searches only the first block i.e.
enough to assign a process.
• It may have problems of not allowing processes to take space even if it was possible
to allocate. Consider the above example, process number 4 (of size 426) does not get
memory. However it was possible to allocate memory if we had allocated using best
fit allocation [block number 4 (of size 300) to process 1, block number 2 to process 2,
block number 3 to process 3 and block number 5 to process 4].
Implementation:
1- Input memory blocks with size and processes with size.
727
Chapter 118. Program for First Fit algorithm in Memory Management
728
Chapter 118. Program for First Fit algorithm in Memory Management
break;
}
}
}
// Driver code
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);
return 0 ;
}
Java
729
Chapter 118. Program for First Fit algorithm in Memory Management
break;
}
}
}
730
Chapter 118. Program for First Fit algorithm in Memory Management
// Driver Code
public static void main(String[] args)
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = blockSize.length;
int n = processSize.length;
C#
class GFG
{
// Method to allocate memory to
// blocks as per First fit algorithm
static void firstFit(int []blockSize, int m,
int []processSize, int n)
{
// Stores block id of the block
// allocated to a process
int []allocation = new int[n];
731
Chapter 118. Program for First Fit algorithm in Memory Management
break;
}
}
}
// Driver Code
public static void Main()
{
int []blockSize = {100, 500, 200, 300, 600};
int []processSize = {212, 417, 112, 426};
int m = blockSize.Length;
int n = processSize.Length;
Output :
Source
https://www.geeksforgeeks.org/program-first-fit-algorithm-memory-management/
732
Chapter 119
733
Chapter 119. Program for Optimal Page Replacement Algorithm
2. If not present, find if a page that is never referenced in future. If such a page exists,
replace this page with new page. If no such page exists, find a page that is referenced
farthest in future. Replace this page with new page.
734
Chapter 119. Program for Optimal Page Replacement Algorithm
// return it.
if (j == pn)
return i;
}
// Driver Function
int main()
{
int pg[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 };
735
Chapter 119. Program for Optimal Page Replacement Algorithm
Output:
No. of hits = 7
No. of misses = 6
• The above implementation can optimized using hashing. We can use an unordered_set
in place of vector so that search operation can be done in O(1) time.
• Note that optimal page replacement algorithm is not practical as we cannot predict
future. However it is used as a reference for other page replacement algorithms.
Source
https://www.geeksforgeeks.org/program-optimal-page-replacement-algorithm/
736
Chapter 120
737
Chapter 120. Program for Page Replacement Algorithms Set 1 ( LRU)
Given memory capacity (as number of pages it can hold) and a string repre-
senting pages to be referred, write a function to find number of page faults.
738
Chapter 120. Program for Page Replacement Algorithms Set 1 ( LRU)
739
Chapter 120. Program for Page Replacement Algorithms Set 1 ( LRU)
{
lru = indexes[*it];
val = *it;
}
}
return page_faults;
}
// Driver code
int main()
{
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
int n = sizeof(pages)/sizeof(pages[0]);
int capacity = 4;
cout << pageFaults(pages, n, capacity);
return 0;
}
Java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
class Test
{
// Method to find page faults using indexes
static int pageFaults(int pages[], int n, int capacity)
{
// To represent set of current pages. We use
740
Chapter 120. Program for Page Replacement Algorithms Set 1 ( LRU)
while (itr.hasNext()) {
int temp = itr.next();
if (indexes.get(temp) < lru)
741
Chapter 120. Program for Page Replacement Algorithms Set 1 ( LRU)
{
lru = indexes.get(temp);
val = temp;
}
}
return page_faults;
}
// Driver method
public static void main(String args[])
{
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
int capacity = 4;
Output:
Note : We can also find the number of page hits. Just have to maintain a separate count.
If the current page is already in the memory then that must be count as Page-hit.
We will discuss other Page-replacement Algorithms in further sets.
742
Chapter 120. Program for Page Replacement Algorithms Set 1 ( LRU)
Source
https://www.geeksforgeeks.org/program-page-replacement-algorithms-set-1-lru/
743
Chapter 121
744
Chapter 121. Program for Page Replacement Algorithms Set 2 (FIFO)
C++
745
Chapter 121. Program for Page Replacement Algorithms Set 2 (FIFO)
indexes.pop();
746
Chapter 121. Program for Page Replacement Algorithms Set 2 (FIFO)
return page_faults;
}
// Driver code
int main()
{
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4,
2, 3, 0, 3, 2};
int n = sizeof(pages)/sizeof(pages[0]);
int capacity = 4;
cout << pageFaults(pages, n, capacity);
return 0;
}
Java
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
class Test
{
// Method to find page faults using FIFO
static int pageFaults(int pages[], int n, int capacity)
{
// To represent set of current pages. We use
// an unordered_set so that we quickly check
// if a page is present in set or not
HashSet<Integer> s = new HashSet<>(capacity);
747
Chapter 121. Program for Page Replacement Algorithms Set 2 (FIFO)
indexes.poll();
return page_faults;
748
Chapter 121. Program for Page Replacement Algorithms Set 2 (FIFO)
// Driver method
public static void main(String args[])
{
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4,
2, 3, 0, 3, 2};
int capacity = 4;
System.out.println(pageFaults(pages, pages.length, capacity));
}
}
// This code is contributed by Gaurav Miglani
Output:
Note – We can also find the number of page hits. Just have to maintain a separate count.
If the current page is already in the memory then that must be count as Page-hit.
Belady’s anomaly –
Belady’s anomaly proves that it is possible to have more page faults when increasing the
number of page frames while using the First in First Out (FIFO) page replacement algorithm.
For example, if we consider reference string 3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4 and 3 slots, we
get 9 total page faults, but if we increase slots to 4, we get 10 page faults.
Improved By : Villan
Source
https://www.geeksforgeeks.org/program-page-replacement-algorithms-set-2-fifo/
749
Chapter 122
Program for Shortest Job First (SJF) scheduling Set 2 (Preemptive) - GeeksforGeeks
In previous post, we have discussed Set 1 of SJF i.e. non-preemptive. In this post we will
discuss the preemptive version of SJF known as Shortest Remaining Time First (SRTF).
In this scheduling algorithm, the process with the smallest amount of time remaining until
completion is selected to execute. Since the currently executing process is the one with the
shortest amount of time remaining by definition, and since that time should only reduce
as execution progresses, processes will always run until they complete or a new process is
added that requires a smaller amount of time.
750
Chapter 122. Program for Shortest Job First (SJF) scheduling Set 2 (Preemptive)
2- The system also requires very little overhead since it only makes a decision when a process
completes or a new process is added.
3- When a new process is added the algorithm only needs to compare the currently executing
process with the new process, ignoring all other processes currently waiting to execute.
Disadvantage:
1- Like shortest job first, it has the potential for process starvation.
2- Long processes may be held off indefinitely if short processes are continually added.
Source:Wiki
Implementation:
1- Traverse until all process gets completely
executed.
a) Find process with minimum remaining time at
every single time lap.
b) Reduce its time by 1.
c) Check if its remaining time becomes 0
d) Increment the counter of process completion.
e) Completion time of current process =
current_time +1;
e) Calculate waiting time for each completed
process.
wt[i]= Completion time - arrival_time-burst_time
f)Increment time lap by one.
2- Find turnaround time (waiting_time+burst_time).
C/C++
struct Process {
int pid; // Process ID
int bt; // Burst Time
int art; // Arrival Time
};
751
Chapter 122. Program for Shortest Job First (SJF) scheduling Set 2 (Preemptive)
if (check == false) {
t++;
continue;
}
// Update minimum
minm = rt[shortest];
if (minm == 0)
minm = INT_MAX;
// Increment complete
complete++;
752
Chapter 122. Program for Shortest Job First (SJF) scheduling Set 2 (Preemptive)
if (wt[shortest] < 0)
wt[shortest] = 0;
}
// Increment time
t++;
}
}
753
Chapter 122. Program for Shortest Job First (SJF) scheduling Set 2 (Preemptive)
// Driver code
int main()
{
Process proc[] = { { 1, 6, 1 }, { 2, 8, 1 },
{ 3, 7, 2 }, { 4, 3, 3 } };
int n = sizeof(proc) / sizeof(proc[0]);
findavgTime(proc, n);
return 0;
}
Java
class Process
{
int pid; // Process ID
int bt; // Burst Time
int art; // Arrival Time
754
Chapter 122. Program for Shortest Job First (SJF) scheduling Set 2 (Preemptive)
int wt[])
{
int rt[] = new int[n];
if (check == false) {
t++;
continue;
}
// Update minimum
minm = rt[shortest];
if (minm == 0)
minm = Integer.MAX_VALUE;
// Increment complete
755
Chapter 122. Program for Shortest Job First (SJF) scheduling Set 2 (Preemptive)
complete++;
if (wt[shortest] < 0)
wt[shortest] = 0;
}
// Increment time
t++;
}
}
756
Chapter 122. Program for Shortest Job First (SJF) scheduling Set 2 (Preemptive)
// Driver Method
public static void main(String[] args)
{
Process proc[] = { new Process(1, 6, 1),
new Process(2, 8, 1),
new Process(3, 7, 2),
new Process(4, 3, 3)};
findavgTime(proc, proc.length);
}
}
Output:
Source
https://www.geeksforgeeks.org/program-shortest-job-first-scheduling-set-2srtf-make-changesdoneplease-review/
757
Chapter 123
Program for Shortest Job First (or SJF) scheduling Set 1 (Non- preemptive) - GeeksforGeeks
Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the wait-
ing process with the smallest execution time to execute next. SJN is a non-preemptive
algorithm.
• Shortest Job first has the advantage of having minimum average waiting time among
all scheduling algorithms.
• It is a Greedy Algorithm.
• It may cause starvation if shorter processes keep coming. This problem can be solved
using the concept of aging.
• It is practically infeasible as Operating System may not know burst time and therefore
may not sort them. While it is not possible to predict execution time, several methods
can be used to estimate the execution time for a job, such as a weighted average of
previous execution times. SJF can be used in specialized environments where accurate
estimates of running time are available.
Algorithm:
758
Chapter 123. Program for Shortest Job First (or SJF) scheduling Set 1 (Non- preemptive)
3. Waiting Time(W.T): Time Difference between turn around time and burst time.
Waiting Time = Turn Around Time – Burst Time
In this post, we have assumed arrival times as 0, so turn around and completion
times are same.
struct Process
{
int pid; // Process ID
int bt; // Burst Time
};
759
Chapter 123. Program for Shortest Job First (or SJF) scheduling Set 1 (Non- preemptive)
760
Chapter 123. Program for Shortest Job First (or SJF) scheduling Set 1 (Non- preemptive)
// Driver code
int main()
{
Process proc[] = {{1, 6}, {2, 8}, {3, 7}, {4, 3}};
int n = sizeof proc / sizeof proc[0];
findavgTime(proc, n);
return 0;
}
Output:
In Set-2 we will discuss the preemptive version of SJF i.e. Shortest Remaining Time First
761
Chapter 123. Program for Shortest Job First (or SJF) scheduling Set 1 (Non- preemptive)
Source
https://www.geeksforgeeks.org/program-shortest-job-first-sjf-scheduling-set-1-non-preemptive/
762
Chapter 124
763
Chapter 124. Program for Worst Fit algorithm in Memory Management
Implementation:
1- Input memory blocks and processes with sizes.
2- Initialize all memory blocks as free.
3- Start by picking each process and find the
maximum block size that can be assigned to
current process i.e., find max(bockSize[1],
blockSize[2],.....blockSize[n]) >
processSize[current], if found then assign
it to the current process.
5- If not then leave that process and keep checking
the further processes.
764
Chapter 124. Program for Worst Fit algorithm in Memory Management
765
Chapter 124. Program for Worst Fit algorithm in Memory Management
// Driver code
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize)/sizeof(blockSize[0]);
int n = sizeof(processSize)/sizeof(processSize[0]);
return 0 ;
}
Java
766
Chapter 124. Program for Worst Fit algorithm in Memory Management
}
}
// Driver Method
public static void main(String[] args)
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = blockSize.length;
int n = processSize.length;
Output:
767
Chapter 124. Program for Worst Fit algorithm in Memory Management
Source
https://www.geeksforgeeks.org/program-worst-fit-algorithm-memory-management/
768
Chapter 125
leftRotate(arr[], d, n)
start
For i = 0 to i < d
Left rotate all elements of arr[] by one
end
769
Chapter 125. Program for array rotation
To rotate by one, store arr[0] in a temporary variable temp, move arr[1] to arr[0], arr[2] to
arr[1] …and finally temp to arr[n-1]
Let us take the same example arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2
Rotate arr[] by one 2 times
We get [2, 3, 4, 5, 6, 7, 1] after first rotation and [ 3, 4, 5, 6, 7, 1, 2] after second rotation.
Below is the implementation of the above approach :
C++
arr[i] = temp;
}
// Function calling
leftRotate(arr, 2, n);
printArray(arr, n);
770
Chapter 125. Program for array rotation
return 0;
}
Java
771
Chapter 125. Program for array rotation
class RotateArray {
/*Function to left rotate arr[] of size n by d*/
void leftRotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
leftRotatebyOne(arr, n);
}
Python3
772
Chapter 125. Program for array rotation
arr[n-1] = temp
C#
class GFG {
/* Function to left rotate arr[]
of size n by d*/
static void leftRotate(int[] arr, int d,
int n)
{
for (int i = 0; i < d; i++)
leftRotatebyOne(arr, n);
}
arr[i] = temp;
}
// Driver code
773
Chapter 125. Program for array rotation
Output :
3 4 5 6 7 1 2
774
Chapter 125. Program for array rotation
// d elements
#include <bits/stdc++.h>
using namespace std;
else
return gcd(b, a % b);
}
while (1) {
int k = j + d;
if (k >= n)
k = k - n;
if (k == i)
break;
arr[j] = arr[k];
j = k;
}
arr[j] = temp;
}
}
775
Chapter 125. Program for array rotation
// Function calling
leftRotate(arr, 2, n);
printArray(arr, n);
return 0;
}
#include <stdio.h>
/*UTILITY FUNCTIONS*/
/* function to print an array */
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
}
776
Chapter 125. Program for array rotation
Java
class RotateArray {
/*Function to left rotate arr[] of siz n by d*/
void leftRotate(int arr[], int d, int n)
{
int i, j, k, temp;
for (i = 0; i < gcd(d, n); i++) {
/* move i-th values of blocks */
temp = arr[i];
j = i;
while (true) {
k = j + d;
if (k >= n)
k = k - n;
if (k == i)
break;
arr[j] = arr[k];
j = k;
}
arr[j] = temp;
}
}
/*UTILITY FUNCTIONS*/
777
Chapter 125. Program for array rotation
{
int i;
for (i = 0; i < size; i++)
System.out.print(arr[i] + " ");
}
Python3
# UTILITY FUNCTIONS
# function to print an array
778
Chapter 125. Program for array rotation
C#
class GFG {
/* Function to left rotate arr[]
of size n by d*/
static void leftRotate(int[] arr, int d,
int n)
{
int i, j, k, temp;
for (i = 0; i < gcd(d, n); i++) {
/* move i-th values of blocks */
temp = arr[i];
j = i;
while (true) {
k = j + d;
if (k >= n)
k = k - n;
if (k == i)
break;
arr[j] = arr[k];
j = k;
}
arr[j] = temp;
}
}
/*UTILITY FUNCTIONS*/
779
Chapter 125. Program for array rotation
// Driver code
public static void Main()
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
leftRotate(arr, 2, 7);
printArray(arr, 7);
}
}
Output :
3 4 5 6 7 1 2
780
Chapter 125. Program for array rotation
Current array:
Current Index Number -> Value
0 -> 0
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 5
6 -> 6
7 -> 7
New array:
Current Index Number -> New Value
0 -> 5
1 -> 6
2 -> 7
3 -> 0
4 -> 1
5 -> 2
6 -> 3
7 -> 4
// main method
public static void main(String[] args)
781
Chapter 125. Program for array rotation
{
int[] array = { 1, 2, 3, 4, 5, 6, 7 };
rotate(array, 2);
print(array);
}
// rotate method
private static void rotate(int[] array, int n)
{
int currIndex = 0, newIndex = 0,
backupVal = array[currIndex], newVal = array[currIndex];
int i = 0, arrLen = array.length;
while (i < arrLen) {
currIndex = newIndex;
newVal = backupVal;
i++;
}
}
Output :
3 4 5 6 7 1 2
782
Chapter 125. Program for array rotation
Source
https://www.geeksforgeeks.org/array-rotation/
783
Chapter 126
784
Chapter 126. Puzzle Message Spreading
After receiving all these messages, student 1 combines all the funny stories with his or her
funny story and send this combined message to each of the other n – 1 students. Hence, the
minimum number of messages is equal to 2n – 2.
Method 2 (Greedy Algorithm):Number the students from 1 to n as S1, S2, S3,……………,
Sn and send the first n – 1 messages as follows : from S1 to S2, from S2 to S3, and so on,
until the message combining the funny stories initially known to students S1, S2, . . . , Sn –
1 is sent to person n. Then send the message combining all the n funny stories from student
n i.e, Sn to students S1, S2, . . . , Sn – 1.
785
Chapter 126. Puzzle Message Spreading
Source
https://www.geeksforgeeks.org/puzzle-message-spreading/
786
Chapter 127
Rearrange a string so that all same characters become d distance away - GeeksforGeeks
Given a string and a positive integer d. Some characters may be repeated in the given
string. Rearrange characters of the given string such that the same characters become d
distance away from each other. Note that there can be many possible rearrangements, the
output should be one of the possible rearrangements. If no such arrangement is possible,
that should also be reported.
Expected time complexity is O(n) where n is length of input string.
Examples:
Input: "abb", d = 2
Output: "bab"
Input: "aacbbc", d = 3
Output: "abcabc"
Input: "geeksforgeeks", d = 3
Output: egkegkesfesor
Input: "aaa", d = 2
Output: Cannot be rearranged
Hint: Alphabet size may be assumed as constant (256) and extra space may be used.
Solution: The idea is to count frequencies of all characters and consider the most frequent
character first and place all occurrences of it as close as possible. After the most frequent
character is placed, repeat the same process for remaining characters.
787
Chapter 127. Rearrange a string so that all same characters become d distance away
788
Chapter 127. Rearrange a string so that all same characters become d distance away
if (largest != i)
{
swap(&freq[i], &freq[largest]);
maxHeapify(freq, largest, heap_size);
}
}
// A utility function to remove the max item or root from max heap
charFreq extractMax(charFreq freq[], int heap_size)
{
charFreq root = freq[0];
if (heap_size > 1)
{
freq[0] = freq[heap_size-1];
maxHeapify(freq, 0, heap_size-1);
}
return root;
}
// The main function that rearranges input string 'str' such that
// two same characters become d distance away
void rearrange(char str[], int d)
{
// Find length of input string
int n = strlen(str);
789
Chapter 127. Rearrange a string so that all same characters become d distance away
(freq[x].f)++;
str[i] = '\0'; // This change is used later
}
// Now one by one extract all distinct characters from max heap
// and put them back in str[] with the d distance constraint
for (int i = 0; i < m; i++)
{
charFreq x = extractMax(freq, MAX-i);
Python
790
Chapter 127. Rearrange a string so that all same characters become d distance away
# A utility function
def toList(string):
t = []
for x in string:
t.append(x)
return t
# A utility function
def toString(l):
return ''.join(l)
791
Chapter 127. Rearrange a string so that all same characters become d distance away
# A utility function to remove the max item or root from max heap
def extractMax(freq, heap_size):
root = freq[0]
if heap_size > 1:
freq[0] = freq[heap_size-1]
maxHeapify(freq, 0, heap_size-1)
return root
# The main function that rearranges input string 'str' such that
# two same characters become d distance away
def rearrange(string, d):
# Find length of input string
n = len(string)
m = 0
freq[x].f+=1
string[i] = '\0'
# Now one by one extract all distinct characters from max heap
# and put them back in str[] with the d distance constraint
for i in xrange(m):
x = extractMax(freq, MAX-i)
792
Chapter 127. Rearrange a string so that all same characters become d distance away
return toString(string)
# Driver program
string = "aabbcc"
print rearrange(toList(string), 3)
Output:
abcabc
Source
https://www.geeksforgeeks.org/rearrange-a-string-so-that-all-same-characters-become-at-least-d-distance-away/
793
Chapter 128
Rearrange characters in a string such that no two adjacent are same - GeeksforGeeks
Given a string with repeated characters, task is rearrange characters in a string so that no
two adjacent characters are same.
Note : It may be assumed that the string has only lowercase English alphabets.
Examples:
Input: aaabc
Output: abaca
Input: aaabb
Output: ababa
Input: aa
Output: Not Possible
Input: aaaabc
Output: Not Possible
794
Chapter 128. Rearrange characters in a string such that no two adjacent are same
and add it to result. After we add, we decrease frequency of the character and we temporarily
move this character out of priority queue so that it is not picked next time.
We have to follow the step to solve this problem, they are:
1. Build a Priority_queue or max_heap, pq that stores characters and their frequencies.
…… Priority_queue or max_heap is built on the bases of frequency of character.
2. Create a temporary Key that will used as the previous visited element ( previous element
in resultant string. Initialize it { char = ‘#’ , freq = ‘-1’ }
3. While pq is not empty.
….. Pop an element and add it to result.
….. Decrease frequency of the popped element by ‘1’
….. Push the previous element back into the priority_queue if it’s frequency > ‘0’
….. Make the current element as previous element for the next iteration.
4. If length of resultant string and original, print “not possible”. Else print result.
Below c++ implementation of above idea
struct Key
{
int freq; // store frequency of character
char ch;
795
Chapter 128. Rearrange characters in a string such that no two adjacent are same
// into a priority_queue
priority_queue< Key > pq;
for (char c = 'a' ; c <= 'z' ; c++)
if (count[c-'a'])
pq.push( Key { count[c-'a'], c} );
// traverse queue
while (!pq.empty())
{
// pop top element from queue and add it
// to string.
Key k = pq.top();
pq.pop();
str = str + k.ch;
796
Chapter 128. Rearrange characters in a string such that no two adjacent are same
rearrangeString(str);
return 0;
}
Output:
babab
Source
https://www.geeksforgeeks.org/rearrange-characters-string-no-two-adjacent/
797
Chapter 129
Illustration:
Let us understand with the following example:
798
Chapter 129. Reverse Delete Algorithm for Minimum Spanning Tree
If we delete highest weight edge of weight 14, graph doesn’t become disconnected, so we
remove it.
799
Chapter 129. Reverse Delete Algorithm for Minimum Spanning Tree
Edges in MST
(3, 4)
(0, 7)
(2, 3)
(2, 5)
(0, 1)
(5, 6)
(2, 8)
(6, 7)
Note : In case of same weight edges, we can pick any edge of the same weight edges.
Below is C++ implementation of above steps.
public:
Graph(int V); // Constructor
800
Chapter 129. Reverse Delete Algorithm for Minimum Spanning Tree
void reverseDeleteMST();
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
801
Chapter 129. Reverse Delete Algorithm for Minimum Spanning Tree
return true;
}
// Driver code
int main()
{
// create the graph given in above fugure
int V = 9;
802
Chapter 129. Reverse Delete Algorithm for Minimum Spanning Tree
Graph g(V);
g.reverseDeleteMST();
return 0;
}
Output :
Edges in MST
(3, 4)
(0, 7)
(2, 3)
(2, 5)
(0, 1)
(5, 6)
(2, 8)
(6, 7)
Total weight of MST is 37
Notes :
References:
https://en.wikipedia.org/wiki/Reverse-delete_algorithm
803
Chapter 129. Reverse Delete Algorithm for Minimum Spanning Tree
Source
https://www.geeksforgeeks.org/reverse-delete-algorithm-minimum-spanning-tree/
804
Chapter 130
Input : a = {1, 2, 3}
b = {1, 100, 3}
Output : -1
No rescheduling will result in equal requests.
Approach: Observe that each element of array b is always added to any one element of
array a exactly once. Thus sum of all elements of array b + sum of all elements of old array
a = sum of all elements of new array a. Let this sum be S. Also all the elements of new
array a are equal. Let each new element is x. If array a has n elements, this gives
805
Chapter 130. Schedule jobs so that each server gets equal load
x * n = S
=> x = S/n ....(1)
Thus all the equal elements of new array a is given by eqn(1). Now to make each a(i) equals
to x we need to add x-a(i) to each element. We will iterate over entire array a and check
whether a(i) can be made equal to x. There are multiple possibilities:
1. a(i) > x: In this case a(i) can never be made equal to x. So output -1.
2. a(i) + b(i) + b(i+1) = x. Simply add b(i) + b(i+1) to a(i) and update b(i), b(i+1) to
zero.
3. a(i) + b(i) = x. Add b(i) to a(i) and update b(i) to zero.
4. a(i) + b(i+1) = x. Add b(i+1) to a(i) and update b(i+1) to zero.
After array a is completely traversed, check whether all elements of array b are zero or not.
If yes then print a(0) otherwise print -1.
Why b(i) is updated to zero after addition?
Consider a test case in which b(i) is neither added to a(i-1) nor a(i). In that case, we
are bounded to add b(i) to a(i+1). Thus while iterating over the array a when we begin
performing computations on element a(i), first we add element b(i-1) to a(i) to take into
consideration above possibility. Now if b(i-1) is already added to a(i-1) or a(i-2) then in
that case it cannot be added to a(i). So to avoid this double addition of b(i) it is updated
to zero.
The stepwise algorithm is:
Implementation:
806
Chapter 130. Schedule jobs so that each server gets equal load
int i;
long long int s = 0;
// Possibility 1
if (a[i] > x)
return -1;
// Possibility 2
int y = a[i] + b[i];
if (i + 1 < n)
y += b[i + 1];
if (y == x) {
a[i] = y;
b[i] = b[i + 1] = 0;
continue;
807
Chapter 130. Schedule jobs so that each server gets equal load
// Possibility 3
if (a[i] + b[i] == x) {
a[i] += b[i];
b[i] = 0;
continue;
}
// Possibility 4
if (i + 1 < n &&
a[i] + b[i + 1] == x) {
a[i] += b[i + 1];
b[i + 1] = 0;
continue;
}
int main()
{
int a[] = { 6, 14, 21, 1 };
int b[] = { 15, 7, 10, 10 };
int n = sizeof(a) / sizeof(a[0]);
cout << solve(a, b, n);
return 0;
}
Output: 21
808
Chapter 130. Schedule jobs so that each server gets equal load
Source
https://www.geeksforgeeks.org/schedule-jobs-server-gets-equal-load/
809
Chapter 131
810
Chapter 131. Scheduling priority tasks in limited time and minimizing loss
1. Initialize total loss as sum of each priority and units. The idea is to initialize result as
maximum, then one by one subtract priorities of tasks that are scheduled.
2. Sort all tasks according to arrival time.
3. Process through each unit of time from 1 to total time. For current time, pick the
highest priority task that is available. Schedule 1 unit of this task and subtract its
priority from total loss.
811
Chapter 131. Scheduling priority tasks in limited time and minimizing loss
return ans;
}
// driver code
int main()
{
int n = 2, t = 3;
int arriv[] = { 1, 2 };
int units[] = { 2, 2 };
int prior[] = { 100, 300 };
812
Chapter 131. Scheduling priority tasks in limited time and minimizing loss
Output:
100
Source
https://www.geeksforgeeks.org/scheduling-priority-tasks-limited-time-minimizing-loss/
813
Chapter 132
U = {1,2,3,4,5}
S = {S1,S2,S3}
S1 = {4,1,3}, Cost(S1) = 5
S2 = {2,5}, Cost(S2) = 10
S3 = {1,4,3,2}, Cost(S3) = 3
There are two possible set covers {S1, S2} with cost 15
and {S2, S3} with cost 13.
Why is it useful?
It was one of Karp’s NP-complete problems, shown to be so in 1972. Other applications:
edge covering, vertex cover
Interesting example: IBM finds computer viruses (wikipedia)
Elements- 5000 known viruses
814
Chapter 132. Set Cover Problem Set 1 (Greedy Approximate Algorithm)
Sets- 9000 substrings of 20 or more consecutive bytes from viruses, not found in ‘good’
code.
A set cover of 180 was found. It suffices to search for these 180 substrings to verify the
existence of known computer viruses.
Another example: Consider General Motors needs to buy a certain amount of varied sup-
plies and there are suppliers that offer various deals for different combinations of materials
(Supplier A: 2 tons of steel + 500 tiles for $x; Supplier B: 1 ton of steel + 2000 tiles for
$y; etc.). You could use set covering to find the best way to get all the materials while
minimizing cost
Source: http://math.mit.edu/~goemans/18434S06/setcover-tamara.pdf
Set Cover is NP-Hard:
There is no polynomial time solution available for this problem as the problem is a known
NP-Hard problem. There is a polynomial time Greedy approximate algorithm, the greedy
algorithm provides a Logn approximate algorithm.
2-Approximate Greedy Algorithm:
Let U be the universe of elements, {S1 , S2 , … Sm } be collection of subsets of U and Cost(S1 ),
C(S2 ), … Cost(Sm ) be costs of subsets.
Example:
Let us consider the above example to understand Greedy Algorithm.
First Iteration:
I = {}
The per new element cost for S1 = Cost(S1 )/S1 – I = 5/3
The per new element cost for S2 = Cost(S2 )/S2 – I = 10/2
The per new element cost for S3 = Cost(S3 )/S3 – I = 3/4
Since S3 has minimum value S3 is added, I becomes {1,4,3,2}.
Second Iteration:
I = {1,4,3,2}
The per new element cost for S1 = Cost(S1 )/S1 – I = 5/0
Note that S1 doesn’t add any new element to I.
The per new element cost for S2 = Cost(S2 )/S2 – I = 10/1
Note that S2 adds only 5 to I.
815
Chapter 132. Set Cover Problem Set 1 (Greedy Approximate Algorithm)
The greedy algorithm provides the optimal solution for above example, but it may not
provide optimal solution all the time. Consider the following example.
S1 = {1, 2}
S2 = {2, 3, 4, 5}
S3 = {6, 7, 8, 9, 10, 11, 12, 13}
S4 = {1, 3, 5, 7, 9, 11, 13}
S5 = {2, 4, 6, 8, 10, 12, 13}
Source:
http://math.mit.edu/~goemans/18434S06/setcover-tamara.pdf
This article is contributed by Harshit. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/set-cover-problem-set-1-greedy-approximate-algorithm/
816
Chapter 133
Two strings are overlapping if prefix of one string is same suffix of other string or vice verse.
The maximum overlap mean length of the matching prefix and suffix is maximum.
Working of above Algorithm:
817
Chapter 133. Shortest Superstring Problem
818
Chapter 133. Shortest Superstring Problem
{
// compare last i characters in str1 with first i
// characters in str2
if (str1.compare(len1-i, i, str2, 0, i) == 0)
{
if (max < i)
{
//update max and str
max = i;
str = str1 + str2.substr(i);
}
}
}
return max;
}
819
Chapter 133. Shortest Superstring Problem
// Driver program
int main()
{
string arr[] = {"catgc", "ctaagt", "gcta", "ttca", "atgcatc"};
int len = sizeof(arr)/sizeof(arr[0]);
return 0;
}
// This code is contributed by Aditya Goel
820
Chapter 133. Shortest Superstring Problem
The above Greedy Algorithm is proved to be 4 approximate (i.e., length of the superstring
generated by this algorithm is never beyond 4 times the shortest possible superstring). This
algorithm is conjectured to 2 approximate (nobody has found case where it generates more
than twice the worst). Conjectured worst case example is {abk , bk c, bk+1 }. For example
{“abb”, “bbc”, “bbb”}, the above algorithm may generate “abbcbbb” (if “abb” and “bbc”
are picked as first pair), but the actual shortest superstring is “abbbc”. Here ratio is 7/5,
but for large k, ration approaches 2.
There exist better approximate algorithms for this problem. Please refer below link.
Shortest Superstring Problem Set 2 (Using Set Cover)
Applications:
Useful in the genome project since it will allow researchers to determine entire coding regions
from a collection of fragmented sections.
Reference:
http://fileadmin.cs.lth.se/cs/Personal/Andrzej_Lingas/superstring.pdf
http://math.mit.edu/~goemans/18434S06/superstring-lele.pdf
This article is contributed by Piyush. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/shortest-superstring-problem/
821
Chapter 134
Find the smallest number such that the sum of its digits is N and it is divisible by .
Examples :
Input : N = 5
Output : 500000
500000 is the smallest number divisible
by 10^5 and sum of digits as 5.
Input : N = 20
Output : 29900000000000000000000
Explanation
To make a number divisible by we need at least N zeros at the end of the number.
To make the number smallest, we append exactly N zeros to the end of the number. Now,
we need to ensure the sum of the digits is N. For this, we will try to make the length of the
number as small as possible to get the answer. Thus we keep on inserting 9 into the number
till the sum doesn’t exceed N. If we have any remainder left, then we keep it as the first
digit (most significant one) so that the resulting number is minimized.
The approach works well for all subtasks but there are 2 corner cases:
1. The first is that the final number may not fit into the data types present in C++/Java.
Since we only need to output the number, we can use strings to store the answer.
822
Chapter 134. Smallest number with sum of digits as N and divisible by 10^N
void digitsNum(int N)
{
// If N = 0 the string will be 0
if (N == 0)
cout << "0\n";
// Driver Code
int main()
{
int N = 5;
cout << "The number is : ";
digitsNum(N);
return 0;
}
Java
823
Chapter 134. Smallest number with sum of digits as N and divisible by 10^N
class GFG
{
// Driver Code
public static void main (String[] args)
{
int N = 5;
System.out.print("The number is : ");
digitsNum(N);
}
}
Python3
824
Chapter 134. Smallest number with sum of digits as N and divisible by 10^N
import math
def digitsNum(N):
print()
# Driver Code
N = 5
print("The number is : ",end="")
digitsNum(N)
C#
class GFG
{
825
Chapter 134. Smallest number with sum of digits as N and divisible by 10^N
if (N == 0)
Console.Write("0");
// Driver Code
public static void Main ()
{
int N = 5;
Console.Write("The number is : ");
digitsNum(N);
}
}
PHP
<?php
// PHP program to find smallest
// number to find smallest number
// with N as sum of digits and
// divisible by 10^N.
function digitsNum($N)
{
// If N = 0 the string will be 0
if ($N == 0)
echo "0\n";
826
Chapter 134. Smallest number with sum of digits as N and divisible by 10^N
echo "\n";
}
// Driver Code
$N = 5;
echo "The number is : ";
digitsNum($N);
Output :
Source
https://www.geeksforgeeks.org/smallest-number-sum-digits-n-divisible-10n/
827
Chapter 135
Smallest subset with sum greater than all other elements - GeeksforGeeks
Given an array of non-negative integers. Our task is to find minimum number of elements
such that their sum should be greater than the sum of rest of the elements of the array.
Examples :
The Brute force approach is to find sum of all the possible subsets and then compare sum
with sum of remaining elements.
The Efficient Approach is to take the largest elements. We sort values in descending
order, then take elements from the largest, until we get strictly more than half of total sum
of the given array.
CPP
828
Chapter 135. Smallest subset with sum greater than all other elements
curr_sum += arr[i];
res++;
// Driver function
int main()
{
int arr[] = {3, 1, 7, 1};
int n = sizeof(arr) / sizeof(arr[0]);
cout << minElements(arr, n) << endl;
return 0;
}
Java
829
Chapter 135. Smallest subset with sum greater than all other elements
class GFG {
curr_sum += arr[i];
res++;
// Driver Code
public static void main (String[] args) {
int arr[] = {3, 1, 7, 1};
int n = arr.length;
System.out.println(minElements(arr, n));
}
}
Python3
830
Chapter 135. Smallest subset with sum greater than all other elements
halfSum = int(halfSum / 2)
res = 0
curr_sum = 0
for i in range(n):
curr_sum += arr[i]
res += 1
return res
# driver code
arr = [3, 1, 7, 1]
n = len(arr)
print(minElements(arr, n) )
C#
class GFG {
831
Chapter 135. Smallest subset with sum greater than all other elements
halfSum = halfSum / 2;
curr_sum += arr[i];
res++;
return res;
}
// Driver Code
public static void Main ()
{
int []arr = {3, 1, 7, 1};
int n = arr.Length;
Console.WriteLine(minElements(arr, n));
}
}
Output:
Source
https://www.geeksforgeeks.org/smallest-subset-sum-greater-elements/
832
Chapter 136
An approach has already been discussed in the previous post. In this post, a solution using
the approach of Largest Sum Contiguous Subarray is discussed. This is based on the fact
that in order to find the minimum contiguous sum we can first make the elements of the
original array negative ie. Replace each ar[i] by -ar[i] and then apply Kadane Algorithm.
Clearly, if this is the max sum formed then the minimum sum would be the negative of this
sum.
Below is the implementation of above approach:
C++
833
Chapter 136. Smallest sum contiguous subarray Set-2
// Driver Code
int main()
{
int arr[] = { 3, -4, 2, -3, -1, 7, -5 };
Java
class GFG
{
834
Chapter 136. Smallest sum contiguous subarray Set-2
// Driver Code
public static void main (String[] args)
{
int arr[] = {3, -4, 2, -3,
-1, 7, -5};
int n = arr.length;
C#
835
Chapter 136. Smallest sum contiguous subarray Set-2
// Driver Code
public static void Main ()
{
int []arr = {3, -4, 2, -3,
-1, 7, -5};
int n = arr.Length;
836
Chapter 136. Smallest sum contiguous subarray Set-2
Output:
Smallest sum: -6
Source
https://www.geeksforgeeks.org/smallest-sum-contiguous-subarray-set-2/
837
Chapter 137
One solution is we can rotate each element around the center, which gives two possibilities
in the array i.e. the value at index ‘i’ or the value at index “length – 1 – i”.
If array has n elements then 2^n combinations possible thus running time would be O(2^n).
Another solution can be make copy of the array and sort the copied array. Then compare
each element of the sorted array with equivalent element of original array and its mirror
image when pivot around center. Sorting the array takes O(n*logn) and 2n comparisons be
required thus running time would be O(n*logn).
C++
838
Chapter 137. Sorting array with reverse around middle
return true;
}
// driver code
int main()
{
int arr[] = { 1, 7, 6, 4, 5, 3, 2, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
if (ifPossible(arr, n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
839
Chapter 137. Sorting array with reverse around middle
return true;
}
// driver code
public static void main(String[] args)
{
int arr[] = { 1, 7, 6, 4, 5, 3, 2, 8 };
int n = arr.length;
if (ifPossible(arr, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
Python 3
cp = [0] * n
840
Chapter 137. Sorting array with reverse around middle
cp.sort()
for i in range(0 , n) :
return True
# Driver code
arr = [1, 7, 6, 4, 5, 3, 2, 8]
n = len(arr)
if (ifPossible(arr, n)):
print("Yes")
else:
print("No")
C#
class GFG {
841
Chapter 137. Sorting array with reverse around middle
return true;
}
// Driver code
public static void Main()
{
int []arr = new int[]{ 1, 7, 6, 4,
5, 3, 2, 8 };
int n = arr.Length;
if (ifPossible(arr, n))
Console.WriteLine( "Yes");
else
Console.WriteLine( "No");
}
}
Output:
Yes
Source
https://www.geeksforgeeks.org/sorting-array-reverse-around-middle/
842
Chapter 138
Input: 90
Output: 22
Explanation: If we add 21 4's, then we
get 84 and then add 6 to it, we get 90.
Input: 10
Output: 2
Explanation: 4 + 6 = 10
4. For numbers that don’t leave a composite remainder when divided by 4, we do fol-
lowing. If remainder is 1, we subtract 9 from it to get the number which is perfectly
divisible by 4. If the remainder is 2, then subtract 6 from it to make n a number which
is perfectly divisible by 4. If the remainder is 3, then subtract 15 from it to make n
perfectly divisible by 4, and 15 can be made up by 9 + 6.
843
Chapter 138. Split n into maximum composite numbers
So the main observation is to make n such that is composes of maximum no of 4’s and the
remaining can be made up by 6 and 9. We won’t need composite numbers more then that,
as the composite numbers above 9 can be made up of 4, 6, and 9.
Below is the implementation of the above approach
C++
// if the remainder is 1
if (rem == 1) {
844
Chapter 138. Split n into maximum composite numbers
n = 143;
cout << count(n) << endl;
return 0;
}
Java
class GFG
{
// function to calculate the maximum number of
// composite numbers adding upto n
static int count(int n)
{
// 4 is the smallest composite number
if (n < 4)
return -1;
845
Chapter 138. Split n into maximum composite numbers
// if the remainder is 1
if (rem == 1) {
846
Chapter 138. Split n into maximum composite numbers
return 0;
}
// Driver program
public static void main (String[] args)
{
int n = 90;
System.out.println(count(n));
n = 143;
System.out.println(count(n));
}
}
Python3
# if remainder is 0, then it is
# perfectly divisible by 4.
if (rem == 0):
return n // 4
# if the remainder is 1
if (rem == 1):
847
Chapter 138. Split n into maximum composite numbers
# Driver Code
n = 90
print(count(n))
n = 143
print(count(n))
C#
class GFG {
848
Chapter 138. Split n into maximum composite numbers
// if the remainder is 1
if (rem == 1) {
849
Chapter 138. Split n into maximum composite numbers
return 0;
}
// Driver program
public static void Main()
{
int n = 90;
Console.WriteLine(count(n));
n = 143;
Console.WriteLine(count(n));
}
}
PHP
<?php
// PHP program to split a number
// into maximum number of
// composite numbers.
// 4 is the smallest
// composite number
if ($n < 4)
return -1;
// if remainder is 0, then it
// is perfectly divisible by 4.
if ($rem == 0)
850
Chapter 138. Split n into maximum composite numbers
return $n / 4;
// if the remainder is 1
if ($rem == 1) {
851
Chapter 138. Split n into maximum composite numbers
}
}
$n = 90;
echo c_ount($n),"\n";
$n = 143;
echo c_ount($n);
Output:
22
34
Source
https://www.geeksforgeeks.org/split-n-maximum-composite-numbers/
852
Chapter 139
A naive approach would be to check if the sum of each contiguous sub-array and it’s
difference from K.
Below is the implementation of the above approach:
853
Chapter 139. Subarray whose absolute sum is closest to K
currSum = 0
# Driver Code
def main():
arr = [15, -3, 5, 2, 7, 6, 34, -6]
n = len(arr)
K = 50
if(i ==-1):
print("The empty array shows minimum Deviation")
return 0
main()
Output:
-3 5 2 7 6 34
854
Chapter 139. Subarray whose absolute sum is closest to K
window technique reduces the complexity by calculating the new sub-array sum using the
previous sub-array sum. Increase the right index till the difference (K-sum) is greater than
zero. The first sub-array with negative (K-sum) is considered, and the next sub-array is
with left index = i+1(where i is the current right index).
Below is the implementation of the above approach:
855
Chapter 139. Subarray whose absolute sum is closest to K
i += 1
return result
# Driver Code
def main():
arr = [15, -3, 5, 2, 7, 6, 34, -6]
n = len(arr)
K = 50
if(i ==-1):
print("The empty array shows minimum Deviation")
return 0
main()
Output:
-3 5 2 7 6 34
Source
https://www.geeksforgeeks.org/subarray-whose-absolute-sum-is-closest-to-k/
856
Chapter 140
Input : a = { 3, 4, 5, 6 }
Output : 15
Explanation :
We can reduce 4 to 3 and 6 to 5 so that we got
rectangle of (3 * 5). Hence area = 15.
Input : a = { 3, 2, 5, 2 }
Output : 0
Naive Approach : Check for all possible four elements of the array and then whichever can
form a rectangle. In these rectangles, separate all those rectangles which are of maximum
area formed by these elements. After getting the rectangles and their areas, sum them all
to get our desired solution.
857
Chapter 140. Sum of Areas of Rectangles possible for an array
Efficient Approach : To get the maximum area rectangle, first sort the elements of the
array in non-increasing array. After sorting, start the procedure to select the elements of
the array. Here, selection of two elements of array (as length of rectangle) is possible if
elements of array are equal (a[i] == a[i+1]) or if length of smaller element a[i+1] is one less
than a[i] (in this case we have our length a[i+1] because a[i] is decreased by 1). One flag
variable is maintained to check that whether we get length and breadth both. After getting
length, set the flag variable, now calculate the breadth in the same way as we have done for
length and sum the area of rectangle. After getting length and breadth both, again set the
flag variable false so that we will now search for a new rectangle. This process is repeated
and lastly, final sum of area is returned.
C++
// Function to find
// area of rectangles
int MaxTotalRectangleArea(int a[],
int n)
{
// sorting the array in
// descending order
sort(a, a + n, greater<int>());
858
Chapter 140. Sum of Areas of Rectangles possible for an array
// length is set to
// a[i+1] so that if
// a[i] a[i+1] is less
// than by 1 then also
// we have the correct
// choice for length
len = a[i + 1];
return sum;
}
859
Chapter 140. Sum of Areas of Rectangles possible for an array
// Driver code
int main()
{
int a[] = { 10, 10, 10, 10,
11, 10, 11, 10,
9, 9, 8, 8 };
int n = sizeof(a) / sizeof(a[0]);
return 0;
}
Java
class GFG
{
// Function to find
// area of rectangles
static int MaxTotalRectangleArea(int []a,
int n)
{
// temporary variable to
// store the length of rectangle
int len = 0;
860
Chapter 140. Sum of Areas of Rectangles possible for an array
// length is set to
// a[i+1] so that if
// a[i] a[i+1] is less
// than by 1 then also
// we have the correct
// choice for length
len = a[i + 1];
861
Chapter 140. Sum of Areas of Rectangles possible for an array
// also so.
i++;
}
}
return sum;
}
// Driver code
public static void main (String args[])
{
int []a = { 10, 10, 10, 10,
11, 10, 11, 10,
9, 9, 8, 8 };
int n = a.length;
System.out.print(MaxTotalRectangleArea(a, n));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Python3
# Function to find
# area of rectangles
def MaxTotalRectangleArea(a, n) :
862
Chapter 140. Sum of Areas of Rectangles possible for an array
if(i != 0) :
i = i + 1
# length is set to
# a[i+1] so that if
# a[i+1] is less than a[i]
# by 1 then also we have
# the correct chice for length
len = a[i + 1]
863
Chapter 140. Sum of Areas of Rectangles possible for an array
return sum
# Driver code
a = [ 10, 10, 10, 10, 11, 10,
11, 10, 9, 9, 8, 8 ]
n = len(a)
C#
class GFG {
// Function to find
// area of rectangles
static int MaxTotalRectangleArea(int []a,
int n)
{
864
Chapter 140. Sum of Areas of Rectangles possible for an array
// length is set to
// a[i+1] so that if
// a[i] a[i+1] is less
// than by 1 then also
// we have the correct
// choice for length
len = a[i + 1];
865
Chapter 140. Sum of Areas of Rectangles possible for an array
return sum;
}
// Driver code
static public void Main ()
{
int []a = { 10, 10, 10, 10,
11, 10, 11, 10,
9, 9, 8, 8 };
int n = a.Length;
Console.WriteLine(
MaxTotalRectangleArea(a, n));
}
}
PHP
<?php
// PHP code to find sum
// of all area rectangle
// possible
// Function to find
// area of rectangles
function MaxTotalRectangleArea( $a, $n)
{
// sorting the array in
// descending order
rsort($a);
866
Chapter 140. Sum of Areas of Rectangles possible for an array
$len;
// length is set to
// a[i+1] so that if
// a[i+1] is less than a[i]
// by 1 then also we have
// the correct chice for length
$len = $a[$i + 1];
867
Chapter 140. Sum of Areas of Rectangles possible for an array
// elements in array
$flag = false;
return $sum;
}
// Driver code
$a = array( 10, 10, 10, 10,
11, 10, 11, 10,
9, 9, 8, 8 );
$n = count($a);
Output :
282
Source
https://www.geeksforgeeks.org/sum-area-rectangles-possible-array/
868
Chapter 141
• Each element of an array lies in the range given at its corresponding index in the range
array.
• Final sum of difference of consecutive elements in the array formed is minimum.
Examples:
Input: range[] = {{2, 4}, {3, 6}, {1, 5}, {1, 3}, {2, 7}}
Output: 0
The result is 0 because the array {3, 3, 3, 3, 3} is choosen
then the sum of difference of consecutive element will be
{ 3-3 + 3-3 + 3-3 + 3-3 } = 0 which the minimum.
Input: range[] = {{1, 3}, {2, 5}, {6, 8}, {1, 2}, {2, 3}}
Output: 7
The result is 7 because if the array {3, 3, 6, 2, 2} is choosen
then the sum of difference of consecutive element will be
{ 3-3 + 6-3 + 2-6 + 2-2 }= 7 which is the minimum.
Approach: A greedy approach has been followed to solve the above problem. Initially we
have to fill the array in such a way that the sum of the difference obtained is minimum. The
greedy approach is as follows:
869
Chapter 141. Sum of minimum difference between consecutive elements of an array
• If the range of the previous index intersects the range of current index then, in this
case, the minimum difference will be 0 and store the highest value and the lowest value
of intersecting range.
• If the lowest value of the range of the previous index is greater then the highest value
for the current index than in this case the least possible sum is the difference in the
lowest value of the previous range and the highest value stored of the current range.
• If the highest range of the previous index is lower than the lowest value of current range
then the minimum sum is the difference in the lowest value stored for the current index
and the highest range of the previous index.
870
Chapter 141. Sum of minimum difference between consecutive elements of an array
ul = v[i].second;
}
}
// case 2
else if (v[i].first > ul) {
// case 3
else if (v[i].second < ll) {
return 0;
}
Java
class GFG
{
871
Chapter 141. Sum of minimum difference between consecutive elements of an array
// sum of difference of
// consecutive element
static int solve(int[][] v, int n)
{
// ul to store upper limit
// ll to store lower limit
int ans, ul, ll;
int first = 0;
int second = 1;
// inititalize the
// answer with 0
ans = 0;
// case 2
else if (v[i][first] > ul)
{
872
Chapter 141. Sum of minimum difference between consecutive elements of an array
// case 3
else if (v[i][second] < ll)
{
// Driver code
public static void main(String []args)
{
// array of range
int[][] v = {{ 1, 3 }, { 2, 5 },
{ 6, 8 }, { 1, 2 },
{ 2, 3 }};
int n = 5;
System.out.println(solve(v, n));
}
}
Python
class pair:
first = 0
second = 0
873
Chapter 141. Sum of minimum difference between consecutive elements of an array
# inititalize the
# answer with 0
ans = 0
# case 2
elif v[i].first > ul:
# case 3
elif v[i].second < ll:
874
Chapter 141. Sum of minimum difference between consecutive elements of an array
# Driver code
# array of range
v = [pair(1, 3), pair(2, 5),
pair(6, 8), pair(1, 2),
pair(2, 3) ]
n = len(v)
print(solve(v, n))
C#
class GFG
{
// function to find minimum
// sum of difference of
// consecutive element
static int solve(int[,] v, int n)
{
// ul to store upper limit
// ll to store lower limit
int ans, ul, ll;
int first = 0;
int second = 1;
// inititalize the
// answer with 0
ans = 0;
875
Chapter 141. Sum of minimum difference between consecutive elements of an array
// case 2
else if (v[i, first] > ul)
{
// case 3
else if (v[i, second] < ll)
{
876
Chapter 141. Sum of minimum difference between consecutive elements of an array
// Driver code
static void Main()
{
// array of range
PHP
<?php
// PHP program for finding the
// minimum sum of difference
// between consecutive elements
// inititalize the
// answer with 0
$ans = 0;
877
Chapter 141. Sum of minimum difference between consecutive elements of an array
// case 2
else if ($v[$i][$first] > $ul)
{
// case 3
else if ($v[$i][$second] < $ll)
{
// Driver code
// array of range
$v = array(array( 1, 3 ),
878
Chapter 141. Sum of minimum difference between consecutive elements of an array
array( 2, 5 ),
array( 6, 8 ),
array( 1, 2 ),
array( 2, 3 ));
$n = 5;
echo(solve($v, $n));
Output:
Source
https://www.geeksforgeeks.org/sum-of-minimum-difference-between-consecutive-elements-of-an-array/
879
Chapter 142
Input : N = 7
L=2
R = 23
Output : 23
Explanation : When X = 16, we get 7 � 16 = 23 which is the maximum value
for all X � [2, 23].
Input : N = 10
L=5
R = 12
Output : 15
Explanation : When X = 5, we get 10 � 5 = 15 which is the maximum value for
all X � [5, 12].
Brute force approach: We can solve this problem using brute force approach by looping
over all integers over the range [L, R] and taking their XOR with N, while keeping a record
of the maximum result encountered so far. The complexity of this algorithm will be O(R –
L), and it is not feasible when the input variables approach high values such as 109 .
Efficient approach: Since the XOR of two bits is 1 if and only if they are complementary
to each other, we need X to have complementary bits to that of N to have the maximum
value. We will iterate from the largest bit (log2 (R)th bit) to the lowest (0th bit). The
following two cases can arise for each bit:
880
Chapter 142. Value in a given range with maximum XOR
1. If the bit is not set, i.e. 0, we will try to set it in X. If setting this bit to 1 results in
X exceeding R, then we will not set it.
2. If the bit is set, i.e. 1, then we will try to unset it in X. If the current value of X
is already greater than or equal to L, then we can safely unset the bit. In the other
case, we will check if setting all of the next sits is enough to keep X >= L. If not,
then we are required to set the current bit. Observe that setting all of the next bits is
equivalent to adding (1 << b) – 1, where b is the current bit.
// Driver function
int main()
{
int n = 7, l = 2, r = 23;
cout << "The output is " << maximumXOR(n, l, r);
return 0;
}
Java
881
Chapter 142. Value in a given range with maximum XOR
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
// Function to calculate the maximum value of
// N ^ X, where X is in the range [L, R]
static int maximumXOR(int n, int l, int r)
{
int x = 0;
for (int i = (int)(Math.log(r)/Math.log(2)); i >= 0; --i)
{
if ((n & (1 << i))>0) // Set bit
{
if ((x > r) || (x + (1 << i) - 1 < l))
x ^= (1 << i);
}
else // Unset bit
{
if ((x ^ (1 << i)) <= r)
x ^= (1 << i);
}
}
return n ^ x;
}
// Driver function
public static void main(String args[])
{
int n = 7, l = 2, r = 23;
System.out.println( "The output is " + maximumXOR(n, l, r));
}
}
Output:
The output is 23
Improved By : tufan_gupta2000
882
Chapter 142. Value in a given range with maximum XOR
Source
https://www.geeksforgeeks.org/value-in-a-given-range-with-maximum-xor/
883
Chapter 143
Input : 4 2
1 2 60
3 4 50
Output :2
1 2 60
3 4 50
Explanation:
Connected components are:
1->2 and 3->4
Therefore, our answer is 2 followed by
1 2 60 and 3 4 50.
Input :9 6
7 4 98
5 9 72
4 6 10
884
Chapter 143. Water Connection Problem
2 8 22
9 7 17
3 1 66
Output :3
2 8 22
3 1 66
5 6 10
Explanation:
Connected components are 3->1,
5->9->7->4->6 and 2->8.
Therefore, our answer is 3 followed by
2 8 22, 3 1 66, 5 6 10
Approach:
Perform DFS from appropriate houses to find all different connected components. The
number of different connected components is our answer t.
The next t lines of the output are the beginning of the connected component, end of the
connected component and the minimum diameter from the start to the end of the connected
component in each line.
Since, tanks can be installed only on the houses having outgoing pipe and no incoming
pipe, therefore these are appropriate houses to start DFS from i.e. perform DFS from such
unvisited houses.
Below is the implementation of above approach:
C++
885
Chapter 143. Water Connection Problem
int ans;
int dfs(int w)
{
if (cd[w] == 0)
return w;
if (wt[w] < ans)
ans = wt[w];
return dfs(cd[w]);
}
while (i < p) {
cd[q] = h;
wt[q] = t;
rd[h] = q;
i++;
}
a.clear();
b.clear();
c.clear();
886
Chapter 143. Water Connection Problem
a.push_back(j);
b.push_back(w);
c.push_back(ans);
}
// driver function
int main()
{
n = 9, p = 6;
memset(rd, 0, sizeof(rd));
memset(cd, 0, sizeof(cd));
memset(wt, 0, sizeof(wt));
int arr[][3] = { { 7, 4, 98 },
{ 5, 9, 72 },
{ 4, 6, 10 },
{ 2, 8, 22 },
{ 9, 7, 17 },
{ 3, 1, 66 } };
solve(arr);
return 0;
}
Java
class GFG {
887
Chapter 143. Water Connection Problem
return dfs(cd[w]);
}
while (i < p)
{
int q = arr[i][0];
int h = arr[i][1];
int t = arr[i][2];
cd[q] = h;
wt[q] = t;
rd[h] = q;
i++;
}
888
Chapter 143. Water Connection Problem
a=new ArrayList<Integer>();
b=new ArrayList<Integer>();
c=new ArrayList<Integer>();
System.out.println(a.size());
// main function
public static void main(String args[])
{
n = 9;
p = 6;
int arr[][] = { { 7, 4, 98 },
{ 5, 9, 72 },
{ 4, 6, 10 },
{ 2, 8, 22 },
{ 9, 7, 17 },
{ 3, 1, 66 } };
solve(arr);
}
889
Chapter 143. Water Connection Problem
Output:
3
2 8 22
3 1 66
5 6 10
Source
https://www.geeksforgeeks.org/water-connection-problem/
890
Chapter 144
Examples:
Approach:
This problem uses greedy technique.
891
Chapter 144. Water drop problem
A drop will mix with another drop if two conditions are met:
1. If the drop is faster than the drop it is mixing with
2. If the position of the faster drop is behind the slower drop.
We use an array of pairs to store the position and the time that ith drop would take to reach
the end of the pipe. Then we sort the array according to the position of the drops. Now
we have a fair idea of which drops lie behind which drops and their respective time taken
to reach the end.More time means less speed and less time means more speed. Now all the
drops before a slower drop will mix with it. And all the drops after the slower drop with
mix with the next slower drop and so on.
For example if the times to reach the end are- 12, 3, 7, 8, 1 (sorted according to positions)
0th drop is slowest, it won’t mix with the next drop
1st drop is faster than the 2nd drop so they will mix and 2nd drop is faster than 3rd drop
so all three will mix together. They cannot mix with the 4th drop because that is faster.
So we use a stack to maintain the local maxima of the times.
No of local maximal + residue(drops after last local maxima) = total no of drops
#include <bits/stdc++.h>
using namespace std;
int drops(int length, int position[], int speed[], int n)
{
// stores position and time taken by a single
// drop to reach the end as a pair
vector<pair<int, double> > m(n);
int i;
for (i = 0; i < n; i++) {
892
Chapter 144. Water drop problem
// driver function
int main()
{
int length = 12; // length of pipe
int position[] = { 10, 8, 0, 5, 3 }; // position of droplets
int speed[] = { 2, 4, 1, 1, 3 }; // speed of each droplets
int n = sizeof(speed)/sizeof(speed[0]);
cout << drops(length, position, speed, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/water-drop-problem/
893
Chapter 145
C/C++
894
Chapter 145. Write a program to print all permutations of a given string
#include <string.h>
Java
895
Chapter 145. Write a program to print all permutations of a given string
{
String str = "ABC";
int n = str.length();
Permutation permutation = new Permutation();
permutation.permute(str, 0, n-1);
}
/**
* permutation function
* @param str string to calculate permutation for
* @param l starting index
* @param r end index
*/
private void permute(String str, int l, int r)
{
if (l == r)
System.out.println(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r);
str = swap(str,l,i);
}
}
}
/**
* Swap Characters at position
* @param a string value
* @param i position 1
* @param j position 2
* @return swapped string
*/
public String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
896
Chapter 145. Write a program to print all permutations of a given string
Python
def toString(List):
return ''.join(List)
C#
class GFG
{
/**
* permutation function
* @param str string to
calculate permutation for
* @param l starting index
* @param r end index
*/
private static void permute(String str,
int l, int r)
897
Chapter 145. Write a program to print all permutations of a given string
{
if (l == r)
Console.WriteLine(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str, l, i);
permute(str, l + 1, r);
str = swap(str, l, i);
}
}
}
/**
* Swap Characters at position
* @param a string value
* @param i position 1
* @param j position 2
* @return swapped string
*/
public static String swap(String a,
int i, int j)
{
char temp;
char[] charArray = a.ToCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
string s = new string(charArray);
return s;
}
// Driver Code
public static void Main()
{
String str = "ABC";
int n = str.Length;
permute(str, 0, n-1);
}
}
PHP
<?php
// PHP program to print all
898
Chapter 145. Write a program to print all permutations of a given string
/**
* permutation function
* @param str string to
* calculate permutation for
* @param l starting index
* @param r end index
*/
function permute($str, $l, $r)
{
if ($l == $r)
echo $str. "\n";
else
{
for ($i = $l; $i <= $r; $i++)
{
$str = swap($str, $l, $i);
permute($str, $l + 1, $r);
$str = swap($str, $l, $i);
}
}
}
/**
* Swap Characters at position
* @param a string value
* @param i position 1
* @param j position 2
* @return swapped string
*/
function swap($a, $i, $j)
{
$temp;
$charArray = str_split($a);
$temp = $charArray[$i] ;
$charArray[$i] = $charArray[$j];
$charArray[$j] = $temp;
return implode($charArray);
}
// Driver Code
$str = "ABC";
$n = strlen($str);
permute($str, 0, $n - 1);
899
Chapter 145. Write a program to print all permutations of a given string
?>
Output:
ABC
ACB
BAC
BCA
CBA
CAB
Source
https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
900