Dynamic Programming
Dynamic Programming
1
Contents
2
Contents
42 Balanced expressions such that given positions have opening brackets 384
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
3
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
55 Choose maximum weight with given weight and value ratio 460
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
57 Coin game winner where every player has three choices 475
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
4
Contents
72 Count all possible paths from top left to bottom right of a mXn matrix 576
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
76 Count binary strings with k times appearing adjacent two set bits 603
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
5
Contents
79 Count even length binary sequences with same sum of first and second
half bits 620
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
93 Count of arrays in which all adjacent elements are such that one of them
divide the another 720
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 723
95 Count of n digit numbers whose sum of digits equals to given sum 730
6
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742
101 Count the number of ways to tile the floor of size n x m using 1 x m
size tiles 778
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 784
102 Count total number of N digit numbers such that the difference be-
tween sum of even and odd digits is 1 785
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
105 Count ways to increase LCS length of two strings by one 798
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 801
106 Count ways to reach the nth stair using step 1, 2 or 3 802
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810
109 Counting pairs when a person can form pair with at most one 831
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 838
7
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 856
112 Different ways to sum n using numbers greater than or equal to m 857
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 861
122 Efficient program to print all prime factors of a given number 918
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 924
126 Find Maximum dot product of two arrays with insertion of 0’s 947
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 950
127 Find all combinations of k-bit numbers with n bits set where 1 <= n
<= k in sorted order 951
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 953
8
Contents
129 Find all distinct subset (or subsequence) sums of an array 961
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 968
130 Find all distinct subset (or subsequence) sums of an array | Set-2 969
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 971
134 Find length of the longest consecutive path from a given starting char-
acter 991
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 999
135 Find longest bitonic sequence such that increasing and decreasing parts
are from two different arrays 1000
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1002
138 Find maximum sum array of length less than or equal to m 1022
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1023
140 Find minimum number of coins that make a given value 1032
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1043
141 Find minimum possible size of array with given rules for removing
elements 1044
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1047
142 Find minimum sum such that one of every three consecutive elements
is taken 1048
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1054
9
Contents
148 Find the largest area rectangular sub-matrix whose sum is equal to k 1099
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1103
149 Find the longest path in a matrix with given constraints 1104
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1108
150 Find the minimum cost to reach destination using a train 1109
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1119
151 Find the probability of reaching all points after N moves from point N1120
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1122
152 Finding the maximum square sub-matrix with all equal elements 1123
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1132
10
Contents
161 How to print maximum number of A’s using given four keys 1194
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1203
169 Largest area rectangular sub-matrix with equal number of 1’s and 0’s 1265
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1269
11
Contents
185 Longest Even Length Substring such that Sum of First and Second
Half is same 1370
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1382
12
Contents
201 Longest subsequence such that difference between adjacents is one 1478
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1485
204 Maximize arr[j] – arr[i] + arr[l] – arr[k], such that i < j < k < l 1504
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1506
207 Maximize the sum of selected numbers from an array to make it empty 1528
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1530
210 Maximum Subarray Sum using Divide and Conquer algorithm 1546
13
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1553
212 Maximum absolute difference between sum of two contiguous sub-arrays 1560
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1571
217 Maximum difference of zeros and ones in binary string | Set 2 (O(n)
time) 1600
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1605
223 Maximum path sum for each position with jumps under divisibility
condition 1633
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1639
225 Maximum path sum that starting with any cell of 0-th row and ending
with any cell of (N-1)-th row 1647
14
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1652
226 Maximum points collected by two persons allowed to meet once 1653
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1656
227 Maximum points from top left of matrix to bottom right and return
back 1657
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1662
229 Maximum profit by buying and selling a share at most k times 1668
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1681
230 Maximum profit by buying and selling a share at most twice 1682
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1691
234 Maximum sub-matrix area having count of 1’s one more than count of
0’s 1711
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1715
236 Maximum subarray sum in an array created after repeated concatenation 1724
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1730
237 Maximum subsequence sum such that no three are consecutive 1731
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1738
241 Maximum sum in a 2 x n grid such that no two elements are adjacent1769
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1772
15
Contents
242 Maximum sum in circular array such that no two elements are adjacent 1773
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1776
243 Maximum sum increasing subsequence from a prefix and a given ele-
ment after prefix is must 1777
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1782
249 Maximum sum such that no two elements are adjacent 1826
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1831
250 Maximum value with the choice of either dividing or considering as it is 1832
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1836
251 Maximum weight path ending at any element of last row in a matrix 1837
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1843
255 Minimum Cost Path with Left, Right, Bottom and Up moves allowed 1864
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1867
16
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1885
262 Minimum cells required to reach destination with jumps equal to cell
values 1906
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1914
265 Minimum cost to make two strings identical by deleting the digits 1925
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1930
266 Minimum cost to reach the top of the floor by climbing stairs 1931
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1941
267 Minimum cost to sort strings using reversal operations of different costs 1942
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1946
17
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1992
276 Minimum number of jumps to reach end | Set 2 (O(n) solution) 2010
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2017
277 Minimum number of single digit primes required whose sum is equal
to N 2018
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2026
278 Minimum number of squares whose sum equals to given number n 2027
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2038
279 Minimum removals from array to make max – min <= K 2039
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2048
280 Minimum splits in a binary string such that every substring is a power
of 4 or 6. 2049
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2054
287 Minimum sum subsequence such that at least one of every four con-
secutive elements is picked 2097
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2104
288 Minimum time to finish tasks without skipping two consecutive 2105
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2114
289 Minimum time to write characters using insert, delete and copy operation 2115
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2117
18
Contents
298 Number of Co-prime pairs obtained from the sum of digits of elements
in the given range 2180
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2186
300 Number of Unique BST with a given key | Dynamic Programming 2191
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2196
301 Number of arrays of size N whose elements are positive integers and
sum is K 2197
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2202
302 Number of circular tours that visit all petrol pumps 2203
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2206
303 Number of decimal numbers of length k, that are strict monotone 2207
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2212
19
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2231
308 Number of ordered pairs such that (Ai & Aj) = 0 2240
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2247
311 Number of paths from source to destination in a directed acyclic graph 2261
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2264
318 Number of ways a convex polygon of n+2 sides can split into triangles
by connecting vertices 2301
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2306
321 Number of ways to form an array with distinct adjacent elements 2315
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2324
322 Number of ways to insert a character to increase the LCS by one 2325
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2328
20
Contents
323 Number of ways to reach Nth floor by taking at-most K leaps 2329
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2336
328 Partition a set into two subsets such that the difference of subset sums
is minimum 2359
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2367
329 Partitioning into two contiguous element subarrays with equal sums 2368
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2371
331 Perfect Sum Problem (Print all subsets with given sum) 2378
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2383
21
Contents
340 Print all possible ways to convert one string into another string | Edit-
Distance 2441
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2449
341 Print equal sum sets of array (Partition Problem) | Set 2 2450
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2459
342 Print equal sum sets of array (Partition problem) | Set 1 2460
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2473
22
Contents
360 Queries to find distance between two nodes of a Binary tree 2593
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2595
362 Remove array end element to maximize the sum of product 2603
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2604
363 Remove minimum elements from either side such that 2*min becomes
more than max 2605
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2610
367 Sequences of given length where every element is more than or equal
to twice of previous 2640
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2650
370 Shortest path with exactly k edges in a directed and weighted graph 2670
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2676
23
Contents
375 Smallest length string with repeated replacement of two distinct adjacent 2706
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2711
376 Smallest number with given sum of digits and sum of square of digits 2712
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2715
24
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2804
390 Super Ugly Number (Number whose prime factors are in given set) 2805
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2808
402 Total number of possible Binary Search Trees and Binary Trees with
n keys 2885
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2895
403 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) 2896
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2897
404 Traversal of tree with k jumps allowed between nodes of same height 2898
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2903
25
Contents
409 Vertex Cover Problem | Set 2 (Dynamic Programming Solution for Tree) 2934
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2939
412 Ways to arrange Balls such that adjacent balls are of different types 2945
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2958
413 Ways to sum to N using array elements with repetition allowed 2959
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2963
26
Chapter 1
DP-01 | Overlapping
Subproblems Property in
Dynamic Programming
27
Chapter 1. DP-01 | Overlapping Subproblems Property in Dynamic Programming
fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/ \
fib(1) fib(0)
We can see that the function fib(3) is being called 2 times. If we would have stored the
value of fib(3), then instead of computing it again, we could have reused the old stored value.
There are following two different ways to store the values so that these values can be reused:
a) Memoization (Top Down)
b) Tabulation (Bottom Up)
a) Memoization (Top Down): The memoized program for a problem is similar to the
recursive version with a small modification that it looks into a lookup table before computing
solutions. We initialize a lookup array with all initial values as NIL. Whenever we need the
solution to a subproblem, we first look into the lookup table. If the precomputed value is
there then we return that value, otherwise, we calculate the value and put the result in the
lookup table so that it can be reused later.
Following is the memoized version for nth Fibonacci Number.
C/C++
28
Chapter 1. DP-01 | Overlapping Subproblems Property in Dynamic Programming
{
if (lookup[n] == NIL)
{
if (n <= 1)
lookup[n] = n;
else
lookup[n] = fib(n-1) + fib(n-2);
}
return lookup[n];
}
int main ()
{
int n = 40;
_initialize();
printf("Fibonacci number is %d ", fib(n));
return 0;
}
Java
29
Chapter 1. DP-01 | Overlapping Subproblems Property in Dynamic Programming
}
public static void main(String[] args)
{
Fibonacci f = new Fibonacci();
int n = 40;
f._initialize();
System.out.println("Fibonacci number is" + " " + f.fib(n));
}
}
// This Code is Contributed by Saket Kumar
Python
C#
30
Chapter 1. DP-01 | Overlapping Subproblems Property in Dynamic Programming
using System;
class GFG
{
static int MAX = 100;
static int NIL = -1;
static int []lookup = new int[MAX];
/* Function to initialize NIL
values in lookup table */
static void initialize()
{
for (int i = 0; i < MAX; i++)
lookup[i] = NIL;
}
/* function for nth Fibonacci number */
static int fib(int n)
{
if (lookup[n] == NIL)
{
if (n <= 1)
lookup[n] = n;
else
lookup[n] = fib(n - 1) + fib(n - 2);
}
return lookup[n];
}
// Driver code
public static void Main()
{
int n = 40;
initialize();
Console.Write("Fibonacci number is" + " " + fib(n));
}
}
// This Code is Contributed by Sam007
b) Tabulation (Bottom Up): The tabulated program for a given problem builds a table
in bottom up fashion and returns the last entry from table. For example, for the same
Fibonacci number, we first calculate fib(0) then fib(1) then fib(2) then fib(3) and so on. So
literally, we are building the solutions of subproblems bottom-up.
Following is the tabulated version for nth Fibonacci Number.
31
Chapter 1. DP-01 | Overlapping Subproblems Property in Dynamic Programming
C/C++
Java
Python
32
Chapter 1. DP-01 | Overlapping Subproblems Property in Dynamic Programming
C#
33
Chapter 1. DP-01 | Overlapping Subproblems Property in Dynamic Programming
// This Code is Contributed by Sam007
PHP
<?php
// PHP program for Tabulated version
function fib($n)
{
$f[$n + 1]=0;
$i;
$f[0] = 0;
$f[1] = 1;
for ($i = 2; $i <= $n; $i++)
$f[$i] = $f[$i - 1] +
$f[$i - 2];
return $f[$n];
}
// Driver Code
$n = 9;
echo("Fibonacci number is ");
echo(fib($n));
// This code is contributed by nitin mittal.
?>
Output:
Fibonacci number is 34
Both Tabulated and Memoized store the solutions of subproblems. In Memoized version,
table is filled on demand while in Tabulated version, starting from the first entry, all entries
are filled one by one. Unlike the Tabulated version, all entries of the lookup table are not
necessarily filled in Memoized version. For example, Memoized solution of the LCS problem
doesn’t necessarily fill all entries.
To see the optimization achieved by Memoized and Tabulated solutions over the basic Re-
cursive solution, see the time taken by following runs for calculating 40th Fibonacci number:
Recursive solution
Memoized solution
Tabulated solution
Time taken by Recursion method is much more than the two Dynamic Programming tech-
niques mentioned above – Memoization and Tabulation!
34
Chapter 1. DP-01 | Overlapping Subproblems Property in Dynamic Programming
Also, see method 2 of Ugly Number post for one more simple example where we have
overlapping subproblems and we store the results of subproblems.
We will be covering Optimal Substructure Property and some more example problems in
future posts on Dynamic Programming.
Try following questions as an exercise of this post.
1) Write a Memoized solution for LCS problem. Note that the Tabular solution is given in
the CLRS book.
2) How would you choose between Memoization and Tabulation?
References:
http://www.youtube.com/watch?v=V5hZoJ6uK-s
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/overlapping-subproblems-property-in-dynamic-programming-dp-1/
35
Chapter 2
36
Chapter 2. DP-02 | Optimal Substructure Property in Dynamic Programming
Source
https://www.geeksforgeeks.org/optimal-substructure-property-in-dynamic-programming-dp-2/
37
Chapter 3
More Examples:
38
Chapter 3. DP-03 | Longest Increasing Subsequence
Optimal Substructure:
Let arr[0..n-1] be the input array and L(i) be the length of the LIS ending at index i such
that arr[i] is the last element of the LIS.
Then, L(i) can be recursively written as:
L(i) = 1 + max( L(j) ) where 0 < j < i and arr[j] < arr[i]; or
L(i) = 1, if no such j exists.
To find the LIS for a given array, we need to return max(L(i)) where 0 < i < n.
Thus, we see the LIS problem satisfies the optimal substructure property as the main prob-
lem can be solved using solutions to subproblems.
Following is a simple recursive implementation of the LIS problem. It follows the recursive
structure discussed above.
C/C++
39
Chapter 3. DP-03 | Longest Increasing Subsequence
Java
40
Chapter 3. DP-03 | Longest Increasing Subsequence
if (n == 1)
return 1;
// 'max_ending_here' is length of LIS ending with arr[n-1]
int res, max_ending_here = 1;
/* Recursively get all LIS ending with arr[0], arr[1] ...
arr[n-2]. If arr[i-1] is smaller than arr[n-1], and
max ending with arr[n-1] needs to be updated, then
update it */
for (int i = 1; i < n; i++)
{
res = _lis(arr, i);
if (arr[i-1] < arr[n-1] && res + 1 > max_ending_here)
max_ending_here = res + 1;
}
// Compare max_ending_here with the overall max. And
// update the overall max if needed
if (max_ref < max_ending_here)
max_ref = max_ending_here;
// Return length of LIS ending with arr[n-1]
return max_ending_here;
}
// The wrapper function for _lis()
static int lis(int arr[], int n)
{
// The max variable holds the result
max_ref = 1;
// The function _lis() stores its result in max
_lis( arr, n);
// returns max
return max_ref;
}
// driver program to test above functions
public static void main(String args[])
{
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int n = arr.length;
System.out.println("Length of lis is "
+ lis(arr, n) + "n");
}
}
41
Chapter 3. DP-03 | Longest Increasing Subsequence
Python
42
Chapter 3. DP-03 | Longest Increasing Subsequence
# lenght of arr
n = len(arr)
# maximum variable holds the result
maximum = 1
# The function _lis() stores its result in maximum
_lis(arr , n)
return maximum
# Driver program to test the above function
arr = [10 , 22 , 9 , 33 , 21 , 50 , 41 , 60]
n = len(arr)
print "Length of lis is ", lis(arr)
# This code is contributed by NIKHIL KUMAR SINGH
Length of lis is 5
Overlapping Subproblems:
Considering the above implementation, following is recursion tree for an array of size 4.
lis(n) gives us the length of LIS for arr[].
lis(4)
/ |
lis(3) lis(2) lis(1)
/ /
lis(2) lis(1) lis(1)
/
lis(1)
We can see that there are many subproblems which are solved again and again. So this
problem has Overlapping Substructure property and recomputation of same subproblems
can be avoided by either using Memoization or Tabulation. Following is a tabluated imple-
mentation for the LIS problem.
C/C++
43
Chapter 3. DP-03 | Longest Increasing Subsequence
{
int *lis, i, j, max = 0;
lis = (int*) malloc ( sizeof( int ) * n );
/* Initialize LIS values for all indexes */
for (i = 0; i < n; i++ )
lis[i] = 1;
/* Compute optimized LIS values in bottom up manner */
for (i = 1; i < n; i++ )
for (j = 0; j < i; j++ )
if ( arr[i] > arr[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* Pick maximum of all LIS values */
for (i = 0; i < n; i++ )
if (max < lis[i])
max = lis[i];
/* Free memory to avoid memory leak */
free(lis);
return max;
}
/* Driver program to test above function */
int main()
{
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of lis is %dn", lis( arr, n ) );
return 0;
}
Java
44
Chapter 3. DP-03 | Longest Increasing Subsequence
Python
45
Chapter 3. DP-03 | Longest Increasing Subsequence
# Pick maximum of all LIS values
for i in range(n):
maximum = max(maximum , lis[i])
return maximum
# end of lis function
# Driver program to test above function
arr = [10, 22, 9, 33, 21, 50, 41, 60]
print "Length of lis is", lis(arr)
# This code is contributed by Nikhil Kumar Singh
Output:
Length of lis is 5
Note that the time complexity of the above Dynamic Programming (DP) solution is O(n^2)
and there is a O(nLogn) solution for the LIS problem. We have not discussed the O(n Log
n) solution here as the purpose of this post is to explain Dynamic Programming with a
simple example. See below post for O(n Log n) solution.
Longest Increasing Subsequence Size (N log N)
Source
https://www.geeksforgeeks.org/longest-increasing-subsequence-dp-3/
46
Chapter 4
47
Chapter 4. DP-04 | Longest Common Subsequence
Examples:
1) Consider the input strings “AGGTAB” and “GXTXAYB”. Last characters match for the
strings. So length of LCS can be written as:
L(“AGGTAB”, “GXTXAYB”) = 1 + L(“AGGTA”, “GXTXAY”)
2) Consider the input strings “ABCDGH” and “AEDFHR. Last characters do not match
for the strings. So length of LCS can be written as:
L(“ABCDGH”, “AEDFHR”) = MAX ( L(“ABCDG”, “AEDFHR”), L(“ABCDGH”,
“AEDFH”) )
So the LCS problem has optimal substructure property as the main problem can be solved
using solutions to subproblems.
2) Overlapping Subproblems:
Following is simple recursive implementation of the LCS problem. The implementation
simply follows the recursive structure mentioned above.
C/C++
48
Chapter 4. DP-04 | Longest Common Subsequence
Java
49
Chapter 4. DP-04 | Longest Common Subsequence
char[] X=s1.toCharArray();
char[] Y=s2.toCharArray();
int m = X.length;
int n = Y.length;
System.out.println("Length of LCS is" + " " +
lcs.lcs( X, Y, m, n ) );
}
}
// This Code is Contributed by Saket Kumar
Python
C#
50
Chapter 4. DP-04 | Longest Common Subsequence
PHP
<?php
// A Naive recursive PHP
// implementation of LCS problem
function lcs($X, $Y, $m, $n)
{
if($m == 0 || $n == 0)
return 0;
else if ($X[$m - 1] == $Y[$n - 1])
return 1 + lcs($X, $Y,
$m - 1, $n - 1);
else
return max(lcs($X, $Y, $m, $n - 1),
lcs($X, $Y, $m - 1, $n));
}
// Driver Code
$X = "AGGTAB";
$Y = "GXTXAYB";
echo "Length of LCS is ";
51
Chapter 4. DP-04 | Longest Common Subsequence
Output:
Length of LCS is 4
Time complexity of the above naive recursive approach is O(2^n) in worst case and worst
case happens when all characters of X and Y mismatch i.e., length of LCS is 0.
Considering the above implementation, following is a partial recursion tree for input strings
“AXYT” and “AYZX”
lcs("AXYT", "AYZX")
/
lcs("AXY", "AYZX") lcs("AXYT", "AYZ")
/ /
lcs("AX", "AYZX") lcs("AXY", "AYZ") lcs("AXY", "AYZ") lcs("AXYT", "AY")
In the above partial recursion tree, lcs(“AXY”, “AYZ”) is being solved twice. If we draw the
complete recursion tree, then we can see that there are many subproblems which are solved
again and again. So this problem has Overlapping Substructure property and recomputation
of same subproblems can be avoided by either using Memoization or Tabulation. Following
is a tabulated implementation for the LCS problem.
C/C++
52
Chapter 4. DP-04 | Longest Common Subsequence
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
/* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */
return L[m][n];
}
/* Utility function to get max of 2 integers */
int max(int a, int b)
{
return (a > b)? a : b;
}
/* Driver program to test above function */
int main()
{
char X[] = "AGGTAB";
char Y[] = "GXTXAYB";
int m = strlen(X);
int n = strlen(Y);
printf("Length of LCS is %d", lcs( X, Y, m, n ) );
return 0;
}
Java
53
Chapter 4. DP-04 | Longest Common Subsequence
Python
54
Chapter 4. DP-04 | Longest Common Subsequence
# declaring the array for storing the dp values
L = [[None]*(n+1) for i in xrange(m+1)]
"""Following steps build L[m+1][n+1] in bottom up fashion
Note: L[i][j] contains length of LCS of X[0..i-1]
and Y[0..j-1]"""
for i in range(m+1):
for j in range(n+1):
if i == 0 or j == 0 :
L[i][j] = 0
elif X[i-1] == Y[j-1]:
L[i][j] = L[i-1][j-1]+1
else:
L[i][j] = max(L[i-1][j] , L[i][j-1])
# L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1]
return L[m][n]
#end of function lcs
# Driver program to test the above function
X = "AGGTAB"
Y = "GXTXAYB"
print "Length of LCS is ", lcs(X, Y)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
55
Chapter 4. DP-04 | Longest Common Subsequence
PHP
<?php
// Dynamic Programming C#
// implementation of LCS problem
function lcs($X , $Y)
{
// find the length of the strings
$m = strlen($X);
$n = strlen($Y) ;
// declaring the array for
56
Chapter 4. DP-04 | Longest Common Subsequence
Output:
Length of LCS is 4
Time Complexity of the above implementation is O(mn) which is much better than the
worst-case time complexity of Naive Recursive implementation.
The above algorithm/code returns only length of LCS. Please see the following post for
printing the LCS.
Printing Longest Common Subsequence
57
Chapter 4. DP-04 | Longest Common Subsequence
Source
https://www.geeksforgeeks.org/longest-common-subsequence-dp-4/
58
Chapter 5
1. Insert
2. Remove
3. Replace
Examples:
59
Chapter 5. DP-05 | Edit Distance
Let us traverse from right corner, there are two possibilities for every pair of character being
traversed.
1. If last characters of two strings are same, nothing much to do. Ignore last characters
and get count for remaining strings. So we recur for lengths m-1 and n-1.
2. Else (If last characters are not same), we consider all operations on ‘str1’, consider all
three operations on last character of first string, recursively compute minimum cost
for all three operations and take minimum of three values.
(a) Insert: Recur for m and n-1
(b) Remove: Recur for m-1 and n
(c) Replace: Recur for m-1 and n-1
60
Chapter 5. DP-05 | Edit Distance
Java
61
Chapter 5. DP-05 | Edit Distance
Python
62
Chapter 5. DP-05 | Edit Distance
C#
63
Chapter 5. DP-05 | Edit Distance
PHP
<?php
// A Naive recursive Python program
// to find minimum number operations
// to convert str1 to str2
function editDistance($str1, $str2,
$m, $n)
{
// If first string is empty,
// the only option is to insert.
// all characters of second
// string into first
if ($m == 0)
return $n;
// If second string is empty,
// the only option is to
// remove all characters of
// first string
if ($n == 0)
return $m;
// If last characters of two
// strings are same, nothing
// much to do. Ignore last
// characters and get count
// for remaining strings.
if ($str1[$m - 1] == $str2[$n - 1])
{
64
Chapter 5. DP-05 | Edit Distance
Output:
The time complexity of above solution is exponential. In worst case, we may end up doing
O(3m ) operations. The worst case happens when none of characters of two strings match.
Below is a recursive call diagram for worst case.
65
Chapter 5. DP-05 | Edit Distance
We can see that many subproblems are solved, again and again, for example, eD(2,2) is
called three times. Since same suproblems are called again, this problem has Overlapping
Subprolems property. So Edit Distance problem has both properties (see thisand this) of a
dynamic programming problem. Like other typical Dynamic Programming(DP) problems,
recomputations of same subproblems can be avoided by constructing a temporary array that
stores results of subproblems.
C++
66
Chapter 5. DP-05 | Edit Distance
Java
67
Chapter 5. DP-05 | Edit Distance
68
Chapter 5. DP-05 | Edit Distance
}
}/*This code is contributed by Rajat Mishra*/
Python
C#
69
Chapter 5. DP-05 | Edit Distance
70
Chapter 5. DP-05 | Edit Distance
PHP
<?php
// A Dynamic Programming based
// Python program for edit
// distance problem
function editDistDP($str1, $str2,
$m, $n)
{
// Fill d[][] in bottom up manner
for ($i = 0; $i <= $m; $i++)
{
for ($j = 0; $j <= $n; $j++)
{
// If first string is empty,
// only option is to insert
// all characters of second string
if ($i == 0)
$dp[$i][$j] = $j ; // Min. operations = j
// If second string is empty,
// only option is to remove
// all characters of second string
else if($j == 0)
$dp[$i][$j] = $i; // Min. operations = i
71
Chapter 5. DP-05 | Edit Distance
Output:
72
Chapter 5. DP-05 | Edit Distance
Source
https://www.geeksforgeeks.org/edit-distance-dp-5/
73
Chapter 6
The path with minimum cost is highlighted in the following figure. The path is (0, 0) –>
(0, 1) –> (1, 2) –> (2, 2). The cost of the path is 8 (1 + 2 + 2 + 3).
74
Chapter 6. DP-06 | Min Cost Path
1) Optimal Substructure
The path to reach (m, n) must be through one of the 3 cells: (m-1, n-1) or (m-1, n) or
(m, n-1). So minimum cost to reach (m, n) can be written as “minimum of the 3 cells plus
cost[m][n]”.
minCost(m, n) = min (minCost(m-1, n-1), minCost(m-1, n), minCost(m, n-1)) + cost[m][n]
2) Overlapping Subproblems
Following is simple recursive implementation of the MCP (Minimum Cost Path) problem.
The implementation simply follows the recursive structure mentioned above.
75
Chapter 6. DP-06 | Min Cost Path
{1, 5, 3} };
printf(" %d ", minCost(cost, 2, 2));
return 0;
}
Java
76
Chapter 6. DP-06 | Min Cost Path
// This code is contributed by Sam007
Python3
C#
77
Chapter 6. DP-06 | Min Cost Path
PHP
<?php
/* A Naive recursive implementation
of MCP(Minimum Cost Path) problem */
78
Chapter 6. DP-06 | Min Cost Path
$R = 3;
$C = 3;
/* Returns cost of minimum
cost path from (0,0) to
(m, n) in mat[R][C]*/
function minCost($cost, $m, $n)
{
global $R;
global $C;
if ($n < 0 || $m < 0)
return PHP_INT_MAX;
else if ($m == 0 && $n == 0)
return $cost[$m][$n];
else
return $cost[$m][$n] +
min1(minCost($cost, $m - 1, $n - 1),
minCost($cost, $m - 1, $n),
minCost($cost, $m, $n - 1) );
}
/* A utility function that
returns minimum of 3 integers */
function min1($x, $y, $z)
{
if ($x < $y)
return ($x < $z)? $x : $z;
else
return ($y < $z)? $y : $z;
}
// Driver Code
$cost = array(array(1, 2, 3),
array (4, 8, 2),
array (1, 5, 3));
echo minCost($cost, 2, 2);
// This code is contributed by mits.
?>
Output:
It should be noted that the above function computes the same subproblems again and again.
79
Chapter 6. DP-06 | Min Cost Path
See the following recursion tree, there are many nodes which apear more than once. Time
complexity of this naive recursive solution is exponential and it is terribly slow.
mC refers to minCost()
mC(2, 2)
/ | \
/ | \
mC(1, 1) mC(1, 2) mC(2, 1)
/ | \ / | \ / | \
/ | \ / | \ / | \
mC(0,0) mC(0,1) mC(1,0) mC(0,1) mC(0,2) mC(1,1) mC(1,0) mC(1,1) mC(2,0)
So the MCP problem has both properties (see thisand this) of a dynamic programming
problem. Like other typical Dynamic Programming(DP) problems, recomputations of same
subproblems can be avoided by constructing a temporary array tc[][] in bottom up manner.
C++
80
Chapter 6. DP-06 | Min Cost Path
Java
81
Chapter 6. DP-06 | Min Cost Path
tc[0][0] = cost[0][0];
/* Initialize first column of total cost(tc) array */
for (i = 1; i <= m; i++)
tc[i][0] = tc[i-1][0] + cost[i][0];
/* Initialize first row of tc array */
for (j = 1; j <= n; j++)
tc[0][j] = tc[0][j-1] + cost[0][j];
/* Construct rest of the tc array */
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
tc[i][j] = min(tc[i-1][j-1],
tc[i-1][j],
tc[i][j-1]) + cost[i][j];
return tc[m][n];
}
/* Driver program to test above functions */
public static void main(String args[])
{
int cost[][]= {{1, 2, 3},
{4, 8, 2},
{1, 5, 3}};
System.out.println(minCost(cost,2,2));
}
}
// This code is contributed by Pankaj Kumar
Python
82
Chapter 6. DP-06 | Min Cost Path
# Initialize first column of total cost(tc) array
for i in range(1, m+1):
tc[i][0] = tc[i-1][0] + cost[i][0]
# Initialize first row of tc array
for j in range(1, n+1):
tc[0][j] = tc[0][j-1] + cost[0][j]
# Construct rest of the tc array
for i in range(1, m+1):
for j in range(1, n+1):
tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]
return tc[m][n]
# Driver program to test above functions
cost = [[1, 2, 3],
[4, 8, 2],
[1, 5, 3]]
print(minCost(cost, 2, 2))
# This code is contributed by Bhavya Jain
C#
83
Chapter 6. DP-06 | Min Cost Path
/* Initialize first column of total cost(tc) array */
for (i = 1; i <= m; i++)
tc[i, 0] = tc[i - 1, 0] + cost[i, 0];
/* Initialize first row of tc array */
for (j = 1; j <= n; j++)
tc[0, j] = tc[0, j - 1] + cost[0, j];
/* Construct rest of the tc array */
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
tc[i, j] = min(tc[i - 1, j - 1],
tc[i - 1, j],
tc[i, j - 1]) + cost[i, j];
return tc[m, n];
}
// Driver program
public static void Main()
{
int [,]cost= {{1, 2, 3},
{4, 8, 2},
{1, 5, 3}};
Console.Write(minCost(cost,2,2));
}
}
// This code is contributed by Sam007.
PHP
<?php
// DP implementation
// of MCP problem
$R = 3;
$C = 3;
function minCost($cost, $m, $n)
{
global $R;
global $C;
// Instead of following line,
// we can use int tc[m+1][n+1]
// or dynamically allocate
// memory to save space. The
// following line is used to keep
84
Chapter 6. DP-06 | Min Cost Path
Output:
85
Chapter 6. DP-06 | Min Cost Path
Time Complexity of the DP implementation is O(mn) which is much better than Naive
Recursive implementation.
Improved By : Sam007, Mithun Kumar, shiv_bhakt, maveriek
Source
https://www.geeksforgeeks.org/min-cost-path-dp-6/
86
Chapter 7
87
Chapter 7. DP-07 | Coin Change
Java
88
Chapter 7. DP-07 | Coin Change
// If n is less than 0 then no
// solution exists
if (n < 0)
return 0;
// If there are no coins and n
// is greater than 0, then no
// solution exist
if (m <=0 && n >= 1)
return 0;
// count is sum of solutions (i)
// including S[m-1] (ii) excluding S[m-1]
return count( S, m - 1, n ) +
count( S, m, n-S[m-1] );
}
// Driver program to test above function
public static void main(String[] args)
{
int i, j;
int arr[] = {1, 2, 3};
int m = arr.length;
System.out.println( count(arr, m, 4));
}
}
// This article is contributed by vt_m.
Python3
89
Chapter 7. DP-07 | Coin Change
C#
90
Chapter 7. DP-07 | Coin Change
// count is sum of solutions (i)
// including S[m-1] (ii) excluding S[m-1]
return count( S, m - 1, n ) +
count( S, m, n - S[m - 1] );
}
// Driver program
public static void Main()
{
int []arr = {1, 2, 3};
int m = arr.Length;
Console.Write( count(arr, m, 4));
}
}
// This code is contributed by Sam007
PHP
<?php
// Recursive PHP program for
// coin change problem.
// Returns the count of ways we can
// sum S[0...m-1] coins to get sum n
function coun($S, $m, $n)
{
// If n is 0 then there is
// 1 solution (do not include
// any coin)
if ($n == 0)
return 1;
// If n is less than 0 then no
// solution exists
if ($n < 0)
return 0;
// If there are no coins and n
// is greater than 0, then no
// solution exist
if ($m <= 0 && $n >= 1)
return 0;
91
Chapter 7. DP-07 | Coin Change
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
92
Chapter 7. DP-07 | Coin Change
93
Chapter 7. DP-07 | Coin Change
Java
94
Chapter 7. DP-07 | Coin Change
Python
C#
95
Chapter 7. DP-07 | Coin Change
PHP
<?php
// PHP program for
// coin change problem.
function count1($S, $m, $n)
96
Chapter 7. DP-07 | Coin Change
{
// We need n+1 rows as
// the table is constructed
// in bottom up manner
// using the base case 0
// value case (n = 0)
$table;
for ($i = 0; $i < $n + 1; $i++)
for ($j = 0; $j < $m; $j++)
$table[$i][$j] = 0;
// Fill the enteries for
// 0 value case (n = 0)
for ($i = 0; $i < $m; $i++)
$table[0][$i] = 1;
// Fill rest of the table
// entries in bottom up manner
for ($i = 1; $i < $n + 1; $i++)
{
for ($j = 0; $j < $m; $j++)
{
// Count of solutions
// including S[j]
$x = ($i-$S[$j] >= 0) ?
$table[$i - $S[$j]][$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);
// This code is contributed by mits
?>
97
Chapter 7. DP-07 | Coin Change
Output:
Java
98
Chapter 7. DP-07 | Coin Change
Python
99
Chapter 7. DP-07 | Coin Change
Source
https://www.geeksforgeeks.org/coin-change-dp-7/
100
Chapter 8
However, the order in which we parenthesize the product affects the number of simple arith-
metic operations needed to compute the product, or the efficiency. For example, suppose A
is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then,
101
Chapter 8. DP-08 | Matrix Chain Multiplication
1) Optimal Substructure:
A simple solution is to place parenthesis at all possible places, calculate the cost for each
placement and return the minimum value. In a chain of matrices of size n, we can place
the first set of parenthesis in n-1 ways. For example, if the given chain is of 4 matrices.
let the chain be ABCD, then there are 3 ways to place first set of parenthesis outer side:
(A)(BCD), (AB)(CD) and (ABC)(D). So when we place a set of parenthesis, we divide the
problem into subproblems of smaller size. Therefore, the problem has optimal substructure
property and can be easily solved using recursion.
Minimum number of multiplication needed to multiply a chain of size n = Minimum of all
n-1 placements (these placements create subproblems of smaller size)
2) Overlapping Subproblems
Following is a recursive implementation that simply follows the above optimal substructure
property.
102
Chapter 8. DP-08 | Matrix Chain Multiplication
Java
103
Chapter 8. DP-08 | Matrix Chain Multiplication
Python3
104
Chapter 8. DP-08 | Matrix Chain Multiplication
C#
105
Chapter 8. DP-08 | Matrix Chain Multiplication
Time complexity of the above naive recursive approach is exponential. It should be noted
that the above function computes the same subproblems again and again. See the following
recursion tree for a matrix chain of size 4. The function MatrixChainOrder(p, 3, 4) is called
two times. We can see that there are many subproblems being called more than once.
106
Chapter 8. DP-08 | Matrix Chain Multiplication
Since same suproblems are called again, this problem has Overlapping Subprolems property.
So Matrix Chain Multiplication problem has both properties (see thisand this) of a dynamic
programming problem. Like other typical Dynamic Programming(DP) problems, recompu-
tations of same subproblems can be avoided by constructing a temporary array m[][] in
bottom up manner.
Dynamic Programming Solution
Following is C/C++ implementation for Matrix Chain Multiplication problem using
Dynamic Programming.
107
Chapter 8. DP-08 | Matrix Chain Multiplication
}
}
}
return m[1][n-1];
}
int main()
{
int arr[] = {1, 2, 3, 4};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Minimum number of multiplications is %d ",
MatrixChainOrder(arr, size));
getchar();
return 0;
}
Java
108
Chapter 8. DP-08 | Matrix Chain Multiplication
{
j = i+L-1;
if(j == n) continue;
m[i][j] = Integer.MAX_VALUE;
for (k=i; k<=j-1; k++)
{
// q = cost/scalar multiplications
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (q < m[i][j])
m[i][j] = q;
}
}
}
return m[1][n-1];
}
// Driver program to test above function
public static void main(String args[])
{
int arr[] = new int[] {1, 2, 3, 4};
int size = arr.length;
System.out.println("Minimum number of multiplications is "+
MatrixChainOrder(arr, size));
}
}
/* This code is contributed by Rajat Mishra*/
Python
109
Chapter 8. DP-08 | Matrix Chain Multiplication
C#
110
Chapter 8. DP-08 | Matrix Chain Multiplication
/* m[i,j] = Minimum number of scalar
multiplications needed
to compute the matrix A[i]A[i+1]...A[j]
= A[i..j] where dimension of A[i] is
p[i-1] x p[i] */
// cost is zero when multiplying
// one matrix.
for (i = 1; i < n; i++)
m[i, i] = 0;
// L is chain length.
for (L = 2; L < n; L++)
{
for (i = 1; i < n-L+1; i++)
{
j = i+L-1;
if(j == n) continue;
m[i, j] = int.MaxValue;
for (k = i; k <= j-1; k++)
{
// q = cost/scalar multiplications
q = m[i, k] + m[k+1, j] +
p[i-1]*p[k]*p[j];
if (q < m[i, j])
m[i, j] = q;
}
}
}
return m[1, n-1];
}
// Driver program to test above function
public static void Main()
{
int []arr = new int[] {1, 2, 3, 4};
int size = arr.Length;
Console.Write("Minimum number of " +
"multiplications is "+
MatrixChainOrder(arr, size));
}
}
// This code is contributed by Sam007
111
Chapter 8. DP-08 | Matrix Chain Multiplication
Output:
Source
https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/
112
Chapter 9
1. A binomial coefficient C(n, k) can be defined as the coefficient of X^k in the expansion
of (1 + X)^n.
2. A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that
k objects can be chosen from among n objects; more formally, the number of k-element
subsets (or k-combinations) of an n-element set.
The Problem
Write a function that takes two parameters n and k and returns the value of Binomial
Coefficient C(n, k). For example, your function should return 6 for n = 4 and k = 2, and it
should return 10 for n = 5 and k = 2.
1) Optimal Substructure
The value of C(n, k) can be recursively calculated using following standard formula for
Binomial Coefficients.
Following is a simple recursive implementation that simply follows the recursive structure
mentioned above.
C/C++
113
Chapter 9. DP-09 | Binomial Coefficient
{
// Base Cases
if (k==0 || k==n)
return 1;
// Recur
return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k);
}
/* Driver program to test above function*/
int main()
{
int n = 5, k = 2;
printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k));
return 0;
}
Java
114
Chapter 9. DP-09 | Binomial Coefficient
Python
C#
115
Chapter 9. DP-09 | Binomial Coefficient
PHP
<?php
// PHP Code for Dynamic Programming |
// Set 9 (Binomial Coefficient)
// Returns value of
// Binomial Coefficient C(n, k)
function binomialCoeff($n, $k)
{
// Base Cases
if ($k==0 || $k==$n)
return 1;
// Recur
return binomialCoeff($n - 1, $k - 1) +
binomialCoeff($n - 1, $k);
}
// Driver Code
$n = 5;
$k = 2;
echo "Value of C","(",$n ,$k,") is "
, binomialCoeff($n, $k);
// This code is contributed by aj_36
?>
Output:
Value of C(52) is 10
2) Overlapping Subproblems
It should be noted that the above function computes the same subproblems again and again.
See the following recursion tree for n = 5 an k = 2. The function C(3, 1) is called two times.
For large values of n, there will be many common subproblems.
C(5, 2)
116
Chapter 9. DP-09 | Binomial Coefficient
/ \
C(4, 1) C(4, 2)
/ \ / \
C(3, 0) C(3, 1) C(3, 1) C(3, 2)
/ \ / \ / \
C(2, 0) C(2, 1) C(2, 0) C(2, 1) C(2, 1) C(2, 2)
/ \ / \ / \
C(1, 0) C(1, 1) C(1, 0) C(1, 1) C(1, 0) C(1, 1)
Since same suproblems are called again, this problem has Overlapping Subproblems prop-
erty. So the Binomial Coefficient problem has both properties (see thisand this) of a dy-
namic programming problem. Like other typical Dynamic Programming(DP) problems,
re-computations of same subproblems can be avoided by constructing a temporary array
C[][] in bottom up manner. Following is Dynamic Programming based implementation.
C
117
Chapter 9. DP-09 | Binomial Coefficient
Java
118
Chapter 9. DP-09 | Binomial Coefficient
Python
C#
119
Chapter 9. DP-09 | Binomial Coefficient
using System;
class GFG {
// Returns value of Binomial Coefficient
// C(n, k)
static int binomialCoeff(int n, int k)
{
int [,]C = new int[n+1,k+1];
int i, j;
// Calculate value of Binomial
// Coefficient in bottom up manner
for (i = 0; i <= n; i++)
{
for (j = 0; j <= Math.Min(i, k); j++)
{
// Base Cases
if (j == 0 || j == i)
C[i,j] = 1;
// Calculate value using previosly
// stored values
else
C[i,j] = C[i-1,j-1] + C[i-1,j];
}
}
return C[n,k];
}
// A utility function to return minimum
// of two integers
static int min(int a, int b)
{
return (a < b) ? a : b;
}
/* Driver program to test above function*/
public static void Main()
{
int n = 5, k = 2;
Console.WriteLine("Value of C(" + n
+ "," + k + ") is "
+ binomialCoeff(n, k));
}
}
120
Chapter 9. DP-09 | Binomial Coefficient
PHP
<?php
// A Dynamic Programming based
// solution that uses table C[][] to
// calculate the Binomial Coefficient
// Returns value of Binomial
// Coefficient C(n, k)
function binomialCoeff( $n, $k)
{
$C = array(array());
$i; $j;
// Caculate value of Binomial
// Coefficient in bottom up manner
for ($i = 0; $i <= $n; $i++)
{
for ($j = 0; $j <= min($i, $k); $j++)
{
// Base Cases
if ($j == 0 || $j == $i)
$C[$i][$j] = 1;
// Calculate value using
// previosly stored values
else
$C[$i][$j] = $C[$i - 1][$j - 1] +
$C[$i - 1][$j];
}
}
return $C[$n][$k];
}
// Driver Code
$n = 5;
$k = 2;
echo "Value of C(" ,$n," ",$k, ") is"," "
, binomialCoeff($n, $k) ;
// This code is contributed by anuj_67.
?>
Output:
121
Chapter 9. DP-09 | Binomial Coefficient
Value of C[5][2] is 10
C/C++
Java
122
Chapter 9. DP-09 | Binomial Coefficient
class GFG {
static int binomialCoeff(int n, int k)
{
int C[] = new int[k + 1];
// nC0 is 1
C[0] = 1;
for (int i = 1; i <= n; i++)
{
// Compute next row of pascal
// triangle using the previous row
for (int j = Math.min(i, k); j > 0; j--)
C[j] = C[j] + C[j-1];
}
return C[k];
}
/* Driver program */
public static void main(String[] args)
{
int n = 5, k = 2;
System.out.printf("Value of C(%d, %d) is %d "
, n, k, binomialCoeff(n, k));
}
}
Python
123
Chapter 9. DP-09 | Binomial Coefficient
return C[k]
# Driver Program to test the above function
n = 5
k = 2
print "Value of C(%d,%d) is %d" %(n,k,binomialCoeff(n,k))
# This code is contribtued by Nikhil Kumar Singh(nickzuck_007)
C#
124
Chapter 9. DP-09 | Binomial Coefficient
PHP
<?php
// PHP program for space optimized
// Dynamic Programming Solution of
// Binomial Coefficient
function binomialCoeff($n, $k)
{
$C = array_fill(0, $k + 1, 0);
$C[0] = 1; // nC0 is 1
for ($i = 1; $i <= $n; $i++)
{
// Compute next row of pascal
// triangle using the previous row
for ($j = min($i, $k); $j > 0; $j--)
$C[$j] = $C[$j] + $C[$j - 1];
}
return $C[$k];
}
// Driver Code
$n = 5; $k = 2;
echo "Value of C[$n, $k] is ".
binomialCoeff($n, $k);
// This code is contributed by mits.
?>
Output:
Value of C[5][2] is 10
125
Chapter 9. DP-09 | Binomial Coefficient
For i = 1:
C[1] = C[1] + C[0] = 0 + 1 = 1 ==>> C(1,1) = 1
For i = 2:
C[2] = C[2] + C[1] = 0 + 1 = 1 ==>> C(2,2) = 1
C[1] = C[1] + C[0] = 1 + 1 = 2 ==>> C(2,2) = 2
For i=3:
C[3] = C[3] + C[2] = 0 + 1 = 1 ==>> C(3,3) = 1
C[2] = C[2] + C[1] = 1 + 2 = 3 ==>> C(3,2) = 3
C[1] = C[1] + C[0] = 2 + 1 = 3 ==>> C(3,1) = 3
For i=4:
C[4] = C[4] + C[3] = 0 + 1 = 1 ==>> C(4,4) = 1
C[3] = C[3] + C[2] = 1 + 3 = 4 ==>> C(4,3) = 4
C[2] = C[2] + C[1] = 3 + 3 = 6 ==>> C(4,2) = 6
C[1] = C[1] + C[0] = 3 + 1 = 4 ==>> C(4,1) = 4
Source
https://www.geeksforgeeks.org/binomial-coefficient-dp-9/
126
Chapter 10
A simple solution is to consider all subsets of items and calculate the total weight and value
of all subsets. Consider the only subsets whose total weight is smaller than W. From all
such subsets, pick the maximum value subset.
1) Optimal Substructure:
To consider all subsets of items, there can be two cases for every item: (1) the item is
included in the optimal subset, (2) not included in the optimal set.
Therefore, the maximum value that can be obtained from n items is max of following two
values.
1) Maximum value obtained by n-1 items and W weight (excluding nth item).
127
Chapter 10. DP-10 | 0-1 Knapsack Problem
2) Value of nth item plus maximum value obtained by n-1 items and W minus weight of the
nth item (including nth item).
If weight of nth item is greater than W, then the nth item cannot be included and case 1 is
the only possibility.
2) Overlapping Subproblems
Following is recursive implementation that simply follows the recursive structure mentioned
above.
C/C++
128
Chapter 10. DP-10 | 0-1 Knapsack Problem
Java
Python
129
Chapter 10. DP-10 | 0-1 Knapsack Problem
# capacity W
def knapSack(W , wt , val , n):
# Base Case
if n == 0 or W == 0 :
return 0
# If weight of the nth item is more than Knapsack of capacity
# W, then this item cannot be included in the optimal solution
if (wt[n-1] > W):
return knapSack(W , wt , val , n-1)
# return the maximum of two cases:
# (1) nth item included
# (2) not included
else:
return max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1),
knapSack(W , wt , val , n-1))
# end of function knapSack
# To test above function
val = [60, 100, 120]
wt = [10, 20, 30]
W = 50
n = len(val)
print knapSack(W , wt , val , n)
# This code is contributed by Nikhil Kumar Singh
C#
130
Chapter 10. DP-10 | 0-1 Knapsack Problem
PHP
<?php
// A Naive recursive implementation
// of 0-1 Knapsack problem
// Returns the maximum value that
// can be put in a knapsack of
// capacity W
function knapSack($W, $wt, $val, $n)
{
// Base Case
131
Chapter 10. DP-10 | 0-1 Knapsack Problem
if ($n == 0 || $W == 0)
return 0;
// If weight of the nth item is
// more than Knapsack capacity
// W, then this item cannot be
// included in the optimal solution
if ($wt[$n - 1] > $W)
return knapSack($W, $wt, $val, $n - 1);
// Return the maximum of two cases:
// (1) nth item included
// (2) not included
else
return max($val[$n - 1] +
knapSack($W - $wt[$n - 1],
$wt, $val, $n - 1),
knapSack($W, $wt, $val, $n-1));
}
// Driver Code
$val = array(60, 100, 120);
$wt = array(10, 20, 30);
$W = 50;
$n = count($val);
echo knapSack($W, $wt, $val, $n);
// This code is contributed by Sam007
?>
Output:
220
It should be noted that the above function computes the same subproblems again and again.
See the following recursion tree, K(1, 1) is being evaluated twice. Time complexity of this
naive recursive solution is exponential (2^n).
132
Chapter 10. DP-10 | 0-1 Knapsack Problem
/ \ / \
/ \ / \
K(1,2) K(1,1) K(1,1) K(1,0)
/ \ / \ / \
/ \ / \ / \
K(0,2) K(0,1) K(0,1) K(0,0) K(0,1) K(0,0)
Recursion tree for Knapsack capacity 2 units and 3 items of 1 unit weight.
Since suproblems are evaluated again, this problem has Overlapping Subprolems property.
So the 0-1 Knapsack 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 K[][] in bottom up
manner. Following is Dynamic Programming based implementation.
C++
133
Chapter 10. DP-10 | 0-1 Knapsack Problem
Java
134
Chapter 10. DP-10 | 0-1 Knapsack Problem
}
}
/*This code is contributed by Rajat Mishra */
Python
C#
135
Chapter 10. DP-10 | 0-1 Knapsack Problem
PHP
<?php
// A Dynamic Programming based solution
136
Chapter 10. DP-10 | 0-1 Knapsack Problem
Output:
220
Time Complexity: O(nW) where n is the number of items and W is the capacity of knapsack.
References:
http://www.es.ele.tue.nl/education/5MC10/Solutions/knapsack.pdf
137
Chapter 10. DP-10 | 0-1 Knapsack Problem
http://www.cse.unl.edu/~goddard/Courses/CSCE310J/Lectures/Lecture8-DynamicProgramming.
pdf
Improved By : Sam007
Source
https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/
138
Chapter 11
139
Chapter 11. DP-11 | Egg Dropping Puzzle
1) If the egg breaks after dropping from xth floor, then we only need to check for floors
lower than x with remaining eggs; so the problem reduces to x-1 floors and n-1 eggs
2) If the egg doesn’t break after dropping from the xth floor, then we only need to check for
floors higher than x; so the problem reduces to k-x floors and n eggs.
Since we need to minimize the number of trials in worst case, we take the maximum of two
cases. We consider the max of above two cases for every floor and choose the floor which
yields minimum number of trials.
2) Overlapping Subproblems
Following is recursive implementation that simply follows the recursive structure mentioned
above.
C
# include <stdio.h>
# include <limits.h>
// A utility function to get maximum of two integers
int max(int a, int b) { return (a > b)? a: b; }
/* Function to get minimum number of trials needed in worst
case with n eggs and k floors */
int eggDrop(int n, int k)
{
// If there are no floors, then no trials needed. OR if there is
// one floor, one trial needed.
if (k == 1 || k == 0)
return k;
// We need k trials for one egg and k floors
if (n == 1)
return k;
int min = INT_MAX, x, res;
// Consider all droppings from 1st floor to kth floor and
// return the minimum of these values plus 1.
for (x = 1; x <= k; x++)
{
140
Chapter 11. DP-11 | Egg Dropping Puzzle
C#
using System;
class GFG {
/* Function to get minimum number of
trials needed in worst case with n
eggs and k floors */
static int eggDrop(int n, int k)
{
// If there are no floors, then
// no trials needed. OR if there
// is one floor, one trial needed.
if (k == 1 || k == 0)
return k;
// We need k trials for one egg
// and k floors
if (n == 1)
return k;
int min = int.MaxValue;
int x, res;
// Consider all droppings from
//1st floor to kth floor and
// return the minimum of these
// values plus 1.
for (x = 1; x <= k; x++)
{
141
Chapter 11. DP-11 | Egg Dropping Puzzle
Output:
Minimum number of trials in worst case with 2 eggs and 10 floors is 4
It should be noted that the above function computes the same subproblems again and again.
See the following partial recursion tree, E(2, 2) is being evaluated twice. There will many
repeated subproblems when you draw the complete recursion tree even for small values of
n and k.
E(2,4)
|
-------------------------------------
| | | |
| | | |
x=1/ x=2/ x=3/ x=4/
/ / .... ....
/ /
E(1,0) E(2,3) E(1,1) E(2,2)
/ /... /
x=1/ .....
/
E(1,0) E(2,2)
/
142
Chapter 11. DP-11 | Egg Dropping Puzzle
......
Since same suproblems are called again, this problem has Overlapping Subprolems property.
So Egg Dropping Puzzle has both properties (see thisand this) of a dynamic programming
problem. Like other typical Dynamic Programming(DP) problems, recomputations of same
subproblems can be avoided by constructing a temporary array eggFloor[][] in bottom up
manner.
Dynamic Programming Solution
Following are the implementations for Egg Dropping problem using Dynamic Programming.
C++
// A Dynamic Programming based C++ Program for the Egg Dropping Puzzle
# include <stdio.h>
# include <limits.h>
// A utility function to get maximum of two integers
int max(int a, int b) { return (a > b)? a: b; }
/* Function to get minimum number of trials needed in worst
case with n eggs and k floors */
int eggDrop(int n, int k)
{
/* A 2D table where entery eggFloor[i][j] will represent minimum
number of trials needed for i eggs and j floors. */
int eggFloor[n+1][k+1];
int res;
int i, j, x;
// We need one trial for one floor and0 trials for 0 floors
for (i = 1; i <= n; i++)
{
eggFloor[i][1] = 1;
eggFloor[i][0] = 0;
}
// We always need j trials for one egg and j floors.
for (j = 1; j <= k; j++)
eggFloor[1][j] = j;
// Fill rest of the entries in table using optimal substructure
// property
for (i = 2; i <= n; i++)
{
for (j = 2; j <= k; j++)
143
Chapter 11. DP-11 | Egg Dropping Puzzle
{
eggFloor[i][j] = INT_MAX;
for (x = 1; x <= j; x++)
{
res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]);
if (res < eggFloor[i][j])
eggFloor[i][j] = res;
}
}
}
// eggFloor[n][k] holds the result
return eggFloor[n][k];
}
/* Driver program to test to pront printDups*/
int main()
{
int n = 2, k = 36;
printf ("nMinimum number of trials in worst case with %d eggs and "
"%d floors is %d \n", n, k, eggDrop(n, k));
return 0;
}
Java
//A Dynamic Programming based Python Program for the Egg Dropping Puzzle
class EggDrop
{
// A utility function to get maximum of two integers
static int max(int a, int b) { return (a > b)? a: b; }
/* Function to get minimum number of trials needed in worst
case with n eggs and k floors */
static int eggDrop(int n, int k)
{
/* A 2D table where entery eggFloor[i][j] will represent minimum
number of trials needed for i eggs and j floors. */
int eggFloor[][] = new int[n+1][k+1];
int res;
int i, j, x;
// We need one trial for one floor and0 trials for 0 floors
for (i = 1; i <= n; i++)
{
eggFloor[i][1] = 1;
eggFloor[i][0] = 0;
}
144
Chapter 11. DP-11 | Egg Dropping Puzzle
// We always need j trials for one egg and j floors.
for (j = 1; j <= k; j++)
eggFloor[1][j] = j;
// Fill rest of the entries in table using optimal substructure
// property
for (i = 2; i <= n; i++)
{
for (j = 2; j <= k; j++)
{
eggFloor[i][j] = Integer.MAX_VALUE;
for (x = 1; x <= j; x++)
{
res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]);
if (res < eggFloor[i][j])
eggFloor[i][j] = res;
}
}
}
// eggFloor[n][k] holds the result
return eggFloor[n][k];
}
/* Driver program to test to pront printDups*/
public static void main(String args[] )
{
int n = 2, k = 10;
System.out.println("Minimum number of trials in worst case with "+n+" eggs and "+k+
" floors is "+eggDrop(n, k));
}
}
/*This code is contributed by Rajat Mishra*/
Python
# A Dynamic Programming based Python Program for the Egg Dropping Puzzle
INT_MAX = 32767
# Function to get minimum number of trials needed in worst
# case with n eggs and k floors
def eggDrop(n, k):
# A 2D table where entery eggFloor[i][j] will represent minimum
# number of trials needed for i eggs and j floors.
eggFloor = [[0 for x in range(k+1)] for x in range(n+1)]
145
Chapter 11. DP-11 | Egg Dropping Puzzle
# We need one trial for one floor and0 trials for 0 floors
for i in range(1, n+1):
eggFloor[i][1] = 1
eggFloor[i][0] = 0
# We always need j trials for one egg and j floors.
for j in range(1, k+1):
eggFloor[1][j] = j
# Fill rest of the entries in table using optimal substructure
# property
for i in range(2, n+1):
for j in range(2, k+1):
eggFloor[i][j] = INT_MAX
for x in range(1, j+1):
res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x])
if res < eggFloor[i][j]:
eggFloor[i][j] = res
# eggFloor[n][k] holds the result
return eggFloor[n][k]
# Driver program to test to pront printDups
n = 2
k = 36
print("Minimum number of trials in worst case with" + str(n) + "eggs and "
+ str(k) + " floors is " + str(eggDrop(n, k)))
# This code is contributed by Bhavya Jain
C#
146
Chapter 11. DP-11 | Egg Dropping Puzzle
147
Chapter 11. DP-11 | Egg Dropping Puzzle
int n = 2, k = 36;
Console.WriteLine("Minimum number of trials "
+ "in worst case with " + n + " eggs and "
+ k + "floors is " + eggDrop(n, k));
}
}
// This code is contributed by Sam007.
PHP
<?php
// A Dynamic Programming based PHP
// Program for the Egg Dropping Puzzle
/* Function to get minimum number
of trials needed in worst
case with n eggs and k floors */
function eggDrop($n, $k)
{
/* A 2D table where entery eggFloor[i][j]
will represent minimum number of
trials needed for i eggs and j floors. */
$eggFloor = array(array());;
// We need one trial for one
// floor and0 trials for 0 floors
for ($i = 1; $i <=$n;$i++)
{
$eggFloor[$i][1] = 1;
$eggFloor[$i][0] = 0;
}
// We always need j trials
// for one egg and j floors.
for ($j = 1; $j <= $k; $j++)
$eggFloor[1][$j] = $j;
// Fill rest of the entries in
// table using optimal substructure
// property
for ($i = 2; $i <= $n; $i++)
{
for ($j = 2; $j <= $k; $j++)
{
$eggFloor[$i][$j] = 999999;
for ($x = 1; $x <= $j; $x++)
148
Chapter 11. DP-11 | Egg Dropping Puzzle
{
$res = 1 + max($eggFloor[$i - 1][$x - 1],
$eggFloor[$i][$j - $x]);
if ($res < $eggFloor[$i][$j])
$eggFloor[$i][$j] = $res;
}
}
}
// eggFloor[n][k] holds the result
return $eggFloor[$n][$k];
}
// Driver Code
$n = 2;
$k = 36;
echo "Minimum number of trials in worst case with " .$n. " eggs and "
.$k. " floors is " .eggDrop($n, $k) ;
// This code is contributed by Sam007
?>
Output :
Source
https://www.geeksforgeeks.org/egg-dropping-puzzle-dp-11/
149
Chapter 12
As another example, if the given sequence is “BBABCBCAB”, then the output should be 7
as “BABCBAB” is the longest palindromic subseuqnce in it. “BBBBB” and “BBCBB” are
also palindromic subsequences of the given sequence, but not the longest ones.
The naive solution for this problem is to generate all subsequences of the given sequence
and find the longest palindromic subsequence. This solution is exponential in term of time
complexity. Let us see how this problem possesses both important properties of a Dynamic
Programming (DP) Problem and can efficiently solved using Dynamic Programming.
1) Optimal Substructure:
Let X[0..n-1] be the input sequence of length n and L(0, n-1) be the length of the longest
palindromic subsequence of X[0..n-1].
If last and first characters of X are same, then L(0, n-1) = L(1, n-2) + 2.
Else L(0, n-1) = MAX (L(1, n-1), L(0, n-2)).
Following is a general recursive solution with all cases handled.
150
Chapter 12. DP-12 | Longest Palindromic Subsequence
// If there are more than two characters, and first and last
// characters are same
Else L(i, j) = L(i + 1, j - 1) + 2
2) Overlapping Subproblems
Following is simple recursive implementation of the LPS problem. The implementation
simply follows the recursive structure mentioned above.
#include<stdio.h>
#include<string.h>
// A utility function to get max of two integers
int max (int x, int y) { return (x > y)? x : y; }
// Returns the length of the longest palindromic subsequence in seq
int lps(char *seq, int i, int j)
{
// Base Case 1: If there is only 1 character
if (i == j)
return 1;
// Base Case 2: If there are only 2 characters and both are same
if (seq[i] == seq[j] && i + 1 == j)
return 2;
// If the first and last characters match
if (seq[i] == seq[j])
return lps (seq, i+1, j-1) + 2;
// If the first and last characters do not match
return max( lps(seq, i, j-1), lps(seq, i+1, j) );
}
/* Driver program to test above functions */
int main()
{
char seq[] = "GEEKSFORGEEKS";
int n = strlen(seq);
printf ("The length of the LPS is %d", lps(seq, 0, n-1));
151
Chapter 12. DP-12 | Longest Palindromic Subsequence
getchar();
return 0;
}
Output:
Considering the above implementation, following is a partial recursion tree for a sequence
of length 6 with all different characters.
L(0, 5)
/ \
/ \
L(1,5) L(0,4)
/ \ / \
/ \ / \
L(2,5) L(1,4) L(1,4) L(0,3)
In the above partial recursion tree, L(1, 4) is being solved twice. If we draw the complete
recursion tree, then we can see that there are many subproblems which are solved again and
again. Since same suproblems are called again, this problem has Overlapping Subprolems
property. So LPS problem has both properties (see thisand this) of a dynamic programming
problem. Like other typical Dynamic Programming(DP) problems, recomputations of same
subproblems can be avoided by constructing a temporary array L[][] in bottom up manner.
Dynamic Programming Solution
C++
152
Chapter 12. DP-12 | Longest Palindromic Subsequence
// Strings of length 1 are palindrome of lentgh 1
for (i = 0; i < n; i++)
L[i][i] = 1;
// Build the table. Note that the lower diagonal values of table are
// useless and not filled in the process. The values are filled in a
// manner similar to Matrix Chain Multiplication DP solution (See
// https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/). cl is length of
// substring
for (cl=2; cl<=n; cl++)
{
for (i=0; i<n-cl+1; i++)
{
j = i+cl-1;
if (str[i] == str[j] && cl == 2)
L[i][j] = 2;
else if (str[i] == str[j])
L[i][j] = L[i+1][j-1] + 2;
else
L[i][j] = max(L[i][j-1], L[i+1][j]);
}
}
return L[0][n-1];
}
/* Driver program to test above functions */
int main()
{
char seq[] = "GEEKS FOR GEEKS";
int n = strlen(seq);
printf ("The lnegth of the LPS is %d", lps(seq));
getchar();
return 0;
}
Java
//A Dynamic Programming based Python Program for the Egg Dropping Puzzle
class LPS
{
// A utility function to get max of two integers
static int max (int x, int y) { return (x > y)? x : y; }
// Returns the length of the longest palindromic subsequence in seq
153
Chapter 12. DP-12 | Longest Palindromic Subsequence
Python
154
Chapter 12. DP-12 | Longest Palindromic Subsequence
# Create a table to store results of subproblems
L = [[0 for x in range(n)] for x in range(n)]
# Strings of length 1 are palindrome of length 1
for i in range(n):
L[i][i] = 1
# Build the table. Note that the lower diagonal values of table are
# useless and not filled in the process. The values are filled in a
# manner similar to Matrix Chain Multiplication DP solution (See
# https://www.geeksforgeeks.org/dynamic-programming-set-8-matrix-chain-multiplication/
# cl is length of substring
for cl in range(2, n+1):
for i in range(n-cl+1):
j = i+cl-1
if str[i] == str[j] and cl == 2:
L[i][j] = 2
elif str[i] == str[j]:
L[i][j] = L[i+1][j-1] + 2
else:
L[i][j] = max(L[i][j-1], L[i+1][j]);
return L[0][n-1]
# Driver program to test above functions
seq = "GEEKS FOR GEEKS"
n = len(seq)
print("The length of the LPS is " + str(lps(seq)))
# This code is contributed by Bhavya Jain
C#
155
Chapter 12. DP-12 | Longest Palindromic Subsequence
156
Chapter 12. DP-12 | Longest Palindromic Subsequence
PHP
<?php
// A Dynamic Programming based
// PHP program for LPS problem
// Returns the length of the
// longest palindromic
// subsequence in seq
// A utility function to get
// max of two integers
// function max( $x, $y)
// { return ($x > $y)? $x : $y; }
// Returns the length of the
// longest palindromic
// subsequence in seq
function lps($str)
{
$n = strlen($str);
$i; $j; $cl;
// Create a table to store
// results of subproblems
$L[][] = array(array());
// Strings of length 1 are
// palindrome of lentgh 1
for ($i = 0; $i < $n; $i++)
$L[$i][$i] = 1;
// Build the table. Note that
// the lower diagonal values
// of table are useless and
// not filled in the process.
// The values are filled in a
// manner similar to Matrix
// Chain Multiplication DP
157
Chapter 12. DP-12 | Longest Palindromic Subsequence
Output:
Time Complexity of the above implementation is O(n^2) which is much better than the
worst case time complexity of Naive Recursive implementation.
This problem is close to the Longest Common Subsequence (LCS) problem. In fact, we can
use LCS as a subroutine to solve this problem. Following is the two step solution that uses
LCS.
1) Reverse the given sequence and store the reverse in another array say rev[0..n-1]
2) LCS of the given sequence and rev[] will be the longest palindromic sequence.
This solution is also a O(n^2) solution.
158
Chapter 12. DP-12 | Longest Palindromic Subsequence
References:
http://users.eecs.northwestern.edu/~dda902/336/hw6-sol.pdf
Improved By : nitin mittal, shiv_bhakt
Source
https://www.geeksforgeeks.org/longest-palindromic-subsequence-dp-12/
159
Chapter 13
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 1 5 8 9 10 17 17 20
And if the prices are as following, then the maximum obtainable value is 24 (by cutting in
eight pieces of length 1)
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 3 5 8 9 10 17 17 20
A naive solution for this problem is to generate all configurations of different pieces and find
the highest priced configuration. This solution is exponential in term of time complexity.
Let us see how this problem possesses both important properties of a Dynamic Programming
(DP) Problem and can efficiently solved using Dynamic Programming.
1) Optimal Substructure:
We can get the best price by making a cut at different positions and comparing the values
obtained after a cut. We can recursively call the same function for a piece obtained after a
cut.
160
Chapter 13. DP-13 | Cutting a Rod
Let cutRod(n) be the required (best possible price) value for a rod of length n. cutRod(n)
can be written as following.
cutRod(n) = max(price[i] + cutRod(n-i-1)) for all i in {0, 1 .. n-1}
2) Overlapping Subproblems
Following is simple recursive implementation of the Rod Cutting problem. The implemen-
tation simply follows the recursive structure mentioned above.
C++
Java
161
Chapter 13. DP-13 | Cutting a Rod
{
/* Returns the best obtainable price for a rod of length
n and price[] as prices of different pieces */
static int cutRod(int price[], int n)
{
if (n <= 0)
return 0;
int max_val = Integer.MIN_VALUE;
// Recursively cut the rod in different pieces and
// compare different configurations
for (int i = 0; i<n; i++)
max_val = Math.max(max_val,
price[i] + cutRod(price, n-i-1));
return max_val;
}
/* Driver program to test above functions */
public static void main(String args[])
{
int arr[] = new int[] {1, 5, 8, 9, 10, 17, 17, 20};
int size = arr.length;
System.out.println("Maximum Obtainable Value is "+
cutRod(arr, size));
}
}
/* This code is contributed by Rajat Mishra */
Python
162
Chapter 13. DP-13 | Cutting a Rod
C#
163
Chapter 13. DP-13 | Cutting a Rod
}
}
// This code is contributed by Sam007
PHP
<?php
// A Naive recursive solution for
// Rod cutting problem
/* Returns the best obtainable
price for a rod of length n and
price[] as prices of different
pieces */
function cutRod( $price, $n)
{
if ($n <= 0)
return 0;
$max_val = PHP_INT_MIN;
// Recursively cut the rod in different
// pieces and compare different
// configurations
for ($i = 0; $i < $n; $i++)
$max_val = max($max_val, $price[$i] +
cutRod($price, $n - $i - 1));
return $max_val;
}
// Driver Code
$arr = array(1, 5, 8, 9, 10, 17, 17, 20);
$size =count($arr);
echo "Maximum Obtainable Value is "
, cutRod($arr, $size);
// This code is contributed anuj_67.
?>
Output:
Considering the above implementation, following is recursion tree for a Rod of length 4.
164
Chapter 13. DP-13 | Cutting a Rod
cR(4)
/ /
/ /
cR(3) cR(2) cR(1) cR(0)
/ | / |
/ | / |
cR(2) cR(1) cR(0) cR(1) cR(0) cR(0)
/ | |
/ | |
cR(1) cR(0) cR(0) cR(0)
/
/
CR(0)
In the above partial recursion tree, cR(2) is being solved twice. We can see that there are
many subproblems which are solved again and again. Since same suproblems are called
again, this problem has Overlapping Subprolems property. So the Rod Cutting problem has
both properties (see thisand this) of a dynamic programming problem. Like other typical
Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided
by constructing a temporary array val[] in bottom up manner.
C++
165
Chapter 13. DP-13 | Cutting a Rod
val[i] = max_val;
}
return val[n];
}
/* Driver program to test above functions */
int main()
{
int arr[] = {1, 5, 8, 9, 10, 17, 17, 20};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Maximum Obtainable Value is %dn", cutRod(arr, size));
getchar();
return 0;
}
Java
166
Chapter 13. DP-13 | Cutting a Rod
cutRod(arr, size));
}
}
/* This code is contributed by Rajat Mishra */
Python
C#
167
Chapter 13. DP-13 | Cutting a Rod
val[0] = 0;
// Build the table val[] in
// bottom up manner and return
// the last entry from the table
for (int i = 1; i<=n; i++)
{
int max_val = int.MinValue;
for (int j = 0; j < i; j++)
max_val = Math.Max(max_val,
price[j] + val[i - j - 1]);
val[i] = max_val;
}
return val[n];
}
// Driver Code
public static void Main()
{
int []arr = new int[] {1, 5, 8, 9, 10, 17, 17, 20};
int size = arr.Length;
Console.WriteLine("Maximum Obtainable Value is " +
cutRod(arr, size));
}
}
// This code is contributed by Sam007
PHP
<?php
// A Dynamic Programming solution for
// Rod cutting problem
/* Returns the best obtainable price
for a rod of length n and price[] as
prices of different pieces */
function cutRod( $price, $n)
{
$val = array();
$val[0] = 0;
$i; $j;
// Build the table val[] in bottom
// up manner and return the last
// entry from the table
168
Chapter 13. DP-13 | Cutting a Rod
Output:
Time Complexity of the above implementation is O(n^2) which is much better than the
worst-case time complexity of Naive Recursive implementation.
Improved By : Sam007, vt_m, aniketmaurya
Source
https://www.geeksforgeeks.org/cutting-a-rod-dp-13/
169
Chapter 14
Solution
This problem is a variation of standard Longest Increasing Subsequence (LIS) problem. We
need a slight change in the Dynamic Programming solution of LIS problem. All we need to
change is to use sum as a criteria instead of length of increasing subsequence.
Following are the Dynamic Programming solution to the problem :
C/C++
170
Chapter 14. DP-14 | Maximum Sum Increasing Subsequence
Java
171
Chapter 14. DP-14 | Maximum Sum Increasing Subsequence
/* Initialize msis values
for all indexes */
for (i = 0; i < n; i++)
msis[i] = arr[i];
/* Compute maximum sum values
in bottom up manner */
for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (arr[i] > arr[j] &&
msis[i] < msis[j] + arr[i])
msis[i] = msis[j] + arr[i];
/* Pick maximum of all
msis values */
for (i = 0; i < n; i++)
if (max < msis[i])
max = msis[i];
return max;
}
// Driver code
public static void main(String args[])
{
int arr[] = new int[]{1, 101, 2, 3, 100, 4, 5};
int n = arr.length;
System.out.println("Sum of maximum sum "+
"increasing subsequence is "+
maxSumIS(arr, n));
}
}
// This code is contributed
// by Rajat Mishra
Python
172
Chapter 14. DP-14 | Maximum Sum Increasing Subsequence
max = 0
msis = [0 for x in range(n)]
# Initialize msis values
# for all indexes
for i in range(n):
msis[i] = arr[i]
# Compute maximum sum
# values in bottom up manner
for i in range(1, n):
for j in range(i):
if (arr[i] > arr[j] and
msis[i] < msis[j] + arr[i]):
msis[i] = msis[j] + arr[i]
# Pick maximum of
# all msis values
for i in range(n):
if max < msis[i]:
max = msis[i]
return max
# Driver Code
arr = [1, 101, 2, 3, 100, 4, 5]
n = len(arr)
print("Sum of maximum sum increasing " +
"subsequence is " +
str(maxSumIS(arr, n)))
# This code is contributed
# by Bhavya Jain
C#
173
Chapter 14. DP-14 | Maximum Sum Increasing Subsequence
PHP
<?php
// Dynamic Programming implementation
// of Maximum Sum Increasing
// Subsequence (MSIS) problem
// maxSumIS() returns the maximum
// sum of increasing subsequence
// in arr[] of size n
function maxSumIS($arr, $n)
174
Chapter 14. DP-14 | Maximum Sum Increasing Subsequence
{
$max = 0;
$msis= array($n);
// Initialize msis values
// for all indexes
for($i = 0; $i < $n; $i++ )
$msis[$i] = $arr[$i];
// Compute maximum sum values
// in bottom up manner
for($i = 1; $i < $n; $i++)
for($j = 0; $j < $i; $j++)
if ($arr[$i] > $arr[$j] &&
$msis[$i] < $msis[$j] + $arr[$i])
$msis[$i] = $msis[$j] + $arr[$i];
// Pick maximum of all msis values
for($i = 0;$i < $n; $i++ )
if ($max < $msis[$i] )
$max = $msis[$i];
return $max;
}
// Driver Code
$arr = array(1, 101, 2, 3, 100, 4, 5);
$n = count($arr);
echo "Sum of maximum sum increasing subsequence is "
.maxSumIS( $arr, $n );
// This code is contributed by Sam007
?>
Output :
175
Chapter 14. DP-14 | Maximum Sum Increasing Subsequence
Source
https://www.geeksforgeeks.org/maximum-sum-increasing-subsequence-dp-14/
176
Chapter 15
177
Chapter 15. DP-15 | Longest Bitonic Subsequence
C++
178
Chapter 15. DP-15 | Longest Bitonic Subsequence
Java
179
Chapter 15. DP-15 | Longest Bitonic Subsequence
all indexes */
int[] lds = new int [n];
for (i = 0; i < n; i++)
lds[i] = 1;
/* Compute LDS values from right to left */
for (i = n-2; i >= 0; i--)
for (j = n-1; j > i; j--)
if (arr[i] > arr[j] && lds[i] < lds[j] + 1)
lds[i] = lds[j] + 1;
/* Return the maximum value of lis[i] + lds[i] - 1*/
int max = lis[0] + lds[0] - 1;
for (i = 1; i < n; i++)
if (lis[i] + lds[i] - 1 > max)
max = lis[i] + lds[i] - 1;
return max;
}
public static void main (String[] args)
{
int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5,
13, 3, 11, 7, 15};
int n = arr.length;
System.out.println("Length of LBS is "+ lbs( arr, n ));
}
}
Python
180
Chapter 15. DP-15 | Longest Bitonic Subsequence
C#
181
Chapter 15. DP-15 | Longest Bitonic Subsequence
182
Chapter 15. DP-15 | Longest Bitonic Subsequence
Output:
Length of LBS is 7
Source
https://www.geeksforgeeks.org/longest-bitonic-subsequence-dp-15/
183
Chapter 16
Input:
graph[][] = { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0} }
which represents the following graph
10
(0)------->(3)
| /|\
5 | |
| | 1
\|/ |
(1)------->(2)
3
Note that the value of graph[i][j] is 0 if i is equal to j
And graph[i][j] is INF (infinite) if there is no edge from vertex i to j.
Output:
Shortest distance matrix
0 5 8 9
INF 0 3 4
184
Chapter 16. DP-16 | Floyd Warshall Algorithm
INF INF 0 1
INF INF INF 0
C/C++
185
Chapter 16. DP-16 | Floyd Warshall Algorithm
/* Initialize the solution matrix same as input graph matrix. Or
we can say the initial values of shortest distances are based
on shortest paths considering no intermediate vertex. */
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];
/* Add all vertices one by one to the set of intermediate vertices.
---> Before start of an iteration, we have shortest distances between all
pairs of vertices such that the shortest distances consider only the
vertices in set {0, 1, 2, .. k-1} as intermediate vertices.
----> After the end of an iteration, vertex no. k is added to the set of
intermediate vertices and the set becomes {0, 1, 2, .. k} */
for (k = 0; k < V; k++)
{
// Pick all vertices as source one by one
for (i = 0; i < V; i++)
{
// Pick all vertices as destination for the
// above picked source
for (j = 0; j < V; j++)
{
// If vertex k is on the shortest path from
// i to j, then update the value of dist[i][j]
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
// Print the shortest distance matrix
printSolution(dist);
}
/* A utility function to print solution */
void printSolution(int dist[][V])
{
printf ("The following matrix shows the shortest distances"
" between every pair of vertices \n");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf ("%7d", dist[i][j]);
186
Chapter 16. DP-16 | Floyd Warshall Algorithm
}
printf("\n");
}
}
// driver program to test above function
int main()
{
/* Let us create the following weighted graph
10
(0)------->(3)
| /|\
5 | |
| | 1
\|/ |
(1)------->(2)
3 */
int graph[V][V] = { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
// Print the solution
floydWarshall(graph);
return 0;
}
Java
187
Chapter 16. DP-16 | Floyd Warshall Algorithm
188
Chapter 16. DP-16 | Floyd Warshall Algorithm
}
System.out.println();
}
}
// Driver program to test above function
public static void main (String[] args)
{
/* Let us create the following weighted graph
10
(0)------->(3)
| /|\
5 | |
| | 1
\|/ |
(1)------->(2)
3 */
int graph[][] = { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
AllPairShortestPath a = new AllPairShortestPath();
// Print the solution
a.floydWarshall(graph);
}
}
// Contributed by Aakash Hasija
Python
189
Chapter 16. DP-16 | Floyd Warshall Algorithm
190
Chapter 16. DP-16 | Floyd Warshall Algorithm
C#
191
Chapter 16. DP-16 | Floyd Warshall Algorithm
192
Chapter 16. DP-16 | Floyd Warshall Algorithm
Console.Write("INF ");
} else {
Console.Write(dist[i, j] + " ");
}
}
Console.WriteLine();
}
}
// Driver Code
public static void Main(string[] args)
{
/* Let us create the following
weighted graph
10
(0)------->(3)
| /|\
5 | |
| | 1
\|/ |
(1)------->(2)
3 */
int[,] graph = { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
AllPairShortestPath a = new AllPairShortestPath();
// Print the solution
a.floydWarshall(graph);
}
}
// This article is contributed by
// Abdul Mateen Mohammed
Output:
Following matrix shows the shortest distances between every pair of vertices
0 5 8 9
INF 0 3 4
INF INF 0 1
INF INF INF 0
193
Chapter 16. DP-16 | Floyd Warshall Algorithm
#include
Source
https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/
194
Chapter 17
DP-17 | Palindrome
Partitioning
This problem is a variation of Matrix Chain Multiplication problem. If the string is palin-
drome, then we simply return 0. Else, like the Matrix Chain Multiplication problem, we try
making cuts at all possible places, recursively calculate the cost for each cut and return the
minimum value.
Let the given string be str and minPalPartion() be the function that returns the fewest cuts
needed for palindrome partitioning. following is the optimal substructure property.
// i is the starting index and j is the ending index. i must be passed as 0 and j as n-1
minPalPartion(str, i, j) = 0 if i == j. // When string is of length 1.
minPalPartion(str, i, j) = 0 if str[i..j] is palindrome.
195
Chapter 17. DP-17 | Palindrome Partitioning
C/C++
196
Chapter 17. DP-17 | Palindrome Partitioning
Java
197
Chapter 17. DP-17 | Palindrome Partitioning
198
Chapter 17. DP-17 | Palindrome Partitioning
str.charAt(j));
else
P[i][j] = (str.charAt(i) ==
str.charAt(j)) && P[i+1][j-1];
// IF str[i..j] is palindrome, then
// C[i][j] is 0
if (P[i][j] == true)
C[i][j] = 0;
else
{
// Make a cut at every possible
// localtion starting from i to j,
// and get the minimum cost cut.
C[i][j] = Integer.MAX_VALUE;
for (k = i; k <= j - 1; k++)
C[i][j] = Integer.min(C[i][j],
C[i][k] + C[k+1][j] + 1);
}
}
}
// Return the min cut value for complete
// string. i.e., str[0..n-1]
return C[0][n-1];
}
// Driver program to test above function
public static void main(String args[])
{
String str = "ababbbabbababa";
System.out.println("Min cuts needed for "+
"Palindrome Partitioning is "+
minPalPartion(str));
}
}
// This code is contributed by Sumit Ghosh
C#
199
Chapter 17. DP-17 | Palindrome Partitioning
200
Chapter 17. DP-17 | Palindrome Partitioning
Output:
201
Chapter 17. DP-17 | Palindrome Partitioning
C++
202
Chapter 17. DP-17 | Palindrome Partitioning
else
P[i][j] = (str[i] == str[j]) && P[i+1][j-1];
}
}
for (i=0; i<n; i++)
{
if (P[0][i] == true)
C[i] = 0;
else
{
C[i] = INT_MAX;
for(j=0;j<i;j++)
{
if(P[j+1][i] == true && 1+C[j]<C[i])
C[i]=1+C[j];
}
}
}
// Return the min cut value for complete string. i.e., str[0..n-1]
return C[n-1];
}
// Driver program to test above function
int main()
{
char str[] = "ababbbabbababa";
printf("Min cuts needed for Palindrome Partitioning is %d",
minPalPartion(str));
return 0;
}
Java
203
Chapter 17. DP-17 | Palindrome Partitioning
204
Chapter 17. DP-17 | Palindrome Partitioning
C[i] = Integer.MAX_VALUE;
for(j = 0; j < i; j++)
{
if(P[j+1][i] == true && 1 +
C[j] < C[i])
C[i] = 1 + C[j];
}
}
}
// Return the min cut value for complete
// string. i.e., str[0..n-1]
return C[n-1];
}
// Driver program to test above function
public static void main(String args[])
{
String str = "ababbbabbababa";
System.out.println("Min cuts needed for "+
"Palindrome Partitioning"+
" is "+ minPalPartion(str));
}
}
// This code is contributed by Sumit Ghosh
C#
205
Chapter 17. DP-17 | Palindrome Partitioning
206
Chapter 17. DP-17 | Palindrome Partitioning
}
}
// Return the min cut value for complete
// string. i.e., str[0..n-1]
return C[n-1];
}
// Driver program
public static void Main()
{
String str = "ababbbabbababa";
Console.Write("Min cuts needed for "+
"Palindrome Partitioning"+
" is "+ minPalPartion(str));
}
}
// This code is contributed by Sam007
Output:
Source
https://www.geeksforgeeks.org/palindrome-partitioning-dp-17/
207
Chapter 18
arr[] = {1, 5, 3}
Output: false
The array cannot be partitioned into equal sum sets.
208
Chapter 18. DP-18 | Partition problem
C/C++
209
Chapter 18. DP-18 | Partition problem
if (sum%2 != 0)
return false;
// Find if there is subset with sum equal to
// half of total sum
return isSubsetSum (arr, n, sum/2);
}
// Driver program to test above function
int main()
{
int arr[] = {3, 1, 5, 9, 12};
int n = sizeof(arr)/sizeof(arr[0]);
if (findPartiion(arr, n) == true)
printf("Can be divided into two subsets "
"of equal sum");
else
printf("Can not be divided into two subsets"
" of equal sum");
return 0;
}
Java
210
Chapter 18. DP-18 | Partition problem
Python3
211
Chapter 18. DP-18 | Partition problem
C#
212
Chapter 18. DP-18 | Partition problem
class GFG
{
// A utility function that returns true if there is a
// subset of arr[] with sun equal to given sum
static bool isSubsetSum (int []arr, int n, int sum)
{
// Base Cases
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
// If last element is greater than sum, then ignore it
if (arr[n-1] > sum)
return isSubsetSum (arr, n-1, sum);
/* else, check if sum can be obtained by any of
the following
(a) including the last element
(b) excluding the last element
*/
return isSubsetSum (arr, n-1, sum) ||
isSubsetSum (arr, n-1, sum-arr[n-1]);
}
// Returns true if arr[] can be partitioned in two
// subsets of equal sum, otherwise false
static bool findPartition (int []arr, int n)
{
// Calculate sum of the elements in array
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// If sum is odd, there cannot be two subsets
// with equal sum
if (sum%2 != 0)
return false;
// Find if there is subset with sum equal to half
// of total sum
return isSubsetSum (arr, n, sum/2);
}
// Driver function
public static void Main ()
{
213
Chapter 18. DP-18 | Partition problem
int []arr = {3, 1, 5, 9, 12};
int n = arr.Length;
if (findPartition(arr, n) == true)
Console.Write("Can be divided into two "+
"subsets of equal sum");
else
Console.Write("Can not be divided into " +
"two subsets of equal sum");
}
}
// This code is contributed by Sam007
Output:
Time Complexity: O(2^n) In worst case, this solution tries two possibilities (whether to
include or exclude) for every element.
Dynamic Programming Solution
The problem can be solved using dynamic programming when the sum of the elements is
not too big. We can create a 2D array part[][] of size (sum/2)*(n+1). And we can construct
the solution in bottom up manner such that every filled entry has following property
C/C++
214
Chapter 18. DP-18 | Partition problem
if (sum%2 != 0)
return false;
bool part[sum/2+1][n+1];
// initialize top row as true
for (i = 0; i <= n; i++)
part[0][i] = true;
// initialize leftmost column, except part[0][0], as 0
for (i = 1; i <= sum/2; i++)
part[i][0] = false;
// Fill the partition table in botton up manner
for (i = 1; i <= sum/2; i++)
{
for (j = 1; j <= n; j++)
{
part[i][j] = part[i][j-1];
if (i >= arr[j-1])
part[i][j] = part[i][j] || part[i - arr[j-1]][j-1];
}
}
/* // uncomment this part to print table
for (i = 0; i <= sum/2; i++)
{
for (j = 0; j <= n; j++)
printf ("%4d", part[i][j]);
printf("\n");
} */
return part[sum/2][n];
}
// Driver program to test above funtion
int main()
{
int arr[] = {3, 1, 1, 2, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
if (findPartiion(arr, n) == true)
printf("Can be divided into two subsets of equal sum");
else
printf("Can not be divided into two subsets of equal sum");
getchar();
return 0;
}
215
Chapter 18. DP-18 | Partition problem
Java
216
Chapter 18. DP-18 | Partition problem
printf("\n");
} */
return part[sum/2][n];
}
/*Driver function to check for above function*/
public static void main (String[] args)
{
int arr[] = {3, 1, 1, 2, 2,1};
int n = arr.length;
if (findPartition(arr, n) == true)
System.out.println("Can be divided into two "
"subsets of equal sum");
else
System.out.println("Can not be divided into"
" two subsets of equal sum");
}
}
/* This code is contributed by Devesh Agrawal */
C#
217
Chapter 18. DP-18 | Partition problem
218
Chapter 18. DP-18 | Partition problem
}
}
// This code is contributed by Sam007.
Output:
Source
https://www.geeksforgeeks.org/partition-problem-dp-18/
219
Chapter 19
The extra spaces includes spaces put at the end of every line except the last one.
The problem is to minimize the following total cost.
Cost of a line = (Number of extra spaces in the line)^3
Total Cost = Sum of costs for all lines
The total extra spaces in line 1, line 2 and line 3 are 0, 2 and 3 respectively.
So optimal value of total cost is 0 + 2*2 + 3*3 = 13
Please note that the total cost function is not sum of extra spaces, but sum of cubes (or
square is also used) of extra spaces. The idea behind this cost function is to balance the
spaces among lines. For example, consider the following two arrangement of same set of
words:
220
Chapter 19. DP-19 | Word Wrap Problem
1) There are 3 lines. One line has 3 extra spaces and all other lines have 0 extra spaces.
Total extra spaces = 3 + 0 + 0 = 3. Total cost = 3*3*3 + 0*0*0 + 0*0*0 = 27.
2) There are 3 lines. Each of the 3 lines has one extra space. Total extra spaces = 1 + 1 +
1 = 3. Total cost = 1*1*1 + 1*1*1 + 1*1*1 = 3.
Total extra spaces are 3 in both scenarios, but second arrangement should be preferred
because extra spaces are balanced in all three lines. The cost function with cubic sum
serves the purpose because the value of total cost in second scenario is less.
Method 1 (Greedy Solution)
The greedy solution is to place as many words as possible in the first line. Then do the
same thing for the second line and so on until all words are placed. This solution gives
optimal solution for many cases, but doesn’t give optimal solution in all cases. For example,
consider the following string “aaa bb cc ddddd” and line width as 6. Greedy method will
produce following output.
aaa bb
cc
ddddd
Extra spaces in the above 3 lines are 0, 4 and 1 respectively. So total cost is 0 + 64 + 1 =
65.
But the above solution is not the best solution. Following arrangement has more balanced
spaces. Therefore less value of total cost function.
aaa
bb cc
ddddd
Extra spaces in the above 3 lines are 3, 1 and 1 respectively. So total cost is 27 + 1 + 1 =
29.
Despite being sub-optimal in some cases, the greedy approach is used by many word pro-
cessors like MS Word and OpenOffice.org Writer.
Method 2 (Dynamic Programming)
The following Dynamic approach strictly follows the algorithm given in solution of Cormen
book. First we compute costs of all possible lines in a 2D table lc[][]. The value lc[i][j]
indicates the cost to put words from i to j in a single line where i and j are indexes of words
in the input sequences. If a sequence of words from i to j cannot fit in a single line, then
lc[i][j] is considered infinite (to avoid it from being a part of the solution). Once we have
the lc[][] table constructed, we can calculate total cost using following recursive formula. In
the following formula, C[j] is the optimized total cost for arranging words from 1 to j.
221
Chapter 19. DP-19 | Word Wrap Problem
The above recursion has overlapping subproblem property. For example, the solution of
subproblem c(2) is used by c(3), C(4) and so on. So Dynamic Programming is used to store
the results of subproblems. The array c[] can be computed from left to right, since each
value depends only on earlier values.
To print the output, we keep track of what words go on what lines, we can keep a parallel
p array that points to where each c value came from. The last line starts at word p[n] and
goes through word n. The previous line starts at word p[p[n]] and goes through word p[n?]
– 1, etc. The function printSolution() uses p[] to print the solution.
In the below program, input is an array l[] that represents lengths of words in a sequence.
The value l[i] indicates length of the ith word (i starts from 1) in theinput sequence.
C/C++
222
Chapter 19. DP-19 | Word Wrap Problem
223
Chapter 19. DP-19 | Word Wrap Problem
printSolution(p, n);
}
int printSolution (int p[], int n)
{
int k;
if (p[n] == 1)
k = 1;
else
k = printSolution (p, p[n]-1) + 1;
printf ("Line number %d: From word no. %d to %d \n", k, p[n], n);
return k;
}
// Driver program to test above functions
int main()
{
int l[] = {3, 2, 2, 5};
int n = sizeof(l)/sizeof(l[0]);
int M = 6;
solveWordWrap (l, n, M);
return 0;
}
Java
224
Chapter 19. DP-19 | Word Wrap Problem
// l[] and M is line width (maximum no. of characters that can fit in a line)
void solveWordWrap (int l[], int n, int M)
{
// For simplicity, 1 extra space is used in all below arrays
// extras[i][j] will have number of extra spaces if words from i
// to j are put in a single line
int extras[][] = new int[n+1][n+1];
// lc[i][j] will have cost of a line which has words from
// i to j
int lc[][]= new int[n+1][n+1];
// c[i] will have total cost of optimal arrangement of words
// from 1 to i
int c[] = new int[n+1];
// p[] is used to print the solution.
int p[] =new int[n+1];
// calculate extra spaces in a single line. The value extra[i][j]
// indicates extra spaces if words from word number i to j are
// placed in a single line
for (int i = 1; i <= n; i++)
{
extras[i][i] = M - l[i-1];
for (int j = i+1; j <= n; j++)
extras[i][j] = extras[i][j-1] - l[j-1] - 1;
}
// Calculate line cost corresponding to the above calculated extra
// spaces. The value lc[i][j] indicates cost of putting words from
// word number i to j in a single line
for (int i = 1; i <= n; i++)
{
for (int j = i; j <= n; j++)
{
if (extras[i][j] < 0)
lc[i][j] = MAX;
else if (j == n && extras[i][j] >= 0)
lc[i][j] = 0;
else
lc[i][j] = extras[i][j]*extras[i][j];
}
}
// Calculate minimum cost and find minimum cost arrangement.
// The value c[j] indicates optimized cost to arrange words
225
Chapter 19. DP-19 | Word Wrap Problem
C#
226
Chapter 19. DP-19 | Word Wrap Problem
227
Chapter 19. DP-19 | Word Wrap Problem
- l[j-1] - 1;
}
// Calculate line cost corresponding to
// the above calculated extra spaces. The
// value lc[i][j] indicates cost of
// putting words from word number i to
// j in a single line
for (int i = 1; i <= n; i++)
{
for (int j = i; j <= n; j++)
{
if (extras[i,j] < 0)
lc[i,j] = MAX;
else if (j == n &&
extras[i,j] >= 0)
lc[i,j] = 0;
else
lc[i,j] = extras[i,j]
* extras[i,j];
}
}
// Calculate minimum cost and find
// minimum cost arrangement. The value
// c[j] indicates optimized cost to
// arrange words from word number
// 1 to j.
c[0] = 0;
for (int j = 1; j <= n; j++)
{
c[j] = MAX;
for (int i = 1; i <= j; i++)
{
if (c[i-1] != MAX && lc[i,j]
!= MAX && (c[i-1] + lc[i,j]
< c[j]))
{
c[j] = c[i-1] + lc[i,j];
p[j] = i;
}
}
}
printSolution(p, n);
}
// Driver code
228
Chapter 19. DP-19 | Word Wrap Problem
Output:
Source
https://www.geeksforgeeks.org/word-wrap-problem-dp-19/
229
Chapter 20
#include<stdio.h>
#include<stdlib.h>
// Structure for a pair
struct pair
{
int a;
int b;
};
230
Chapter 20. DP-20 | Maximum Length Chain of Pairs
// This function assumes that arr[] is sorted in increasing order
// according the first (or smaller) values in pairs.
int maxChainLength( struct pair arr[], int n)
{
int i, j, max = 0;
int *mcl = (int*) malloc ( sizeof( int ) * n );
/* Initialize MCL (max chain length) values for all indexes */
for ( i = 0; i < n; i++ )
mcl[i] = 1;
/* Compute optimized chain length values in bottom up manner */
for ( i = 1; i < n; i++ )
for ( j = 0; j < i; j++ )
if ( arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1)
mcl[i] = mcl[j] + 1;
// mcl[i] now stores the maximum chain length ending with pair i
/* Pick maximum of all MCL values */
for ( i = 0; i < n; i++ )
if ( max < mcl[i] )
max = mcl[i];
/* Free memory to avoid memory leak */
free( mcl );
return max;
}
/* Driver program to test above function */
int main()
{
struct pair arr[] = { {5, 24}, {15, 25},
{27, 40}, {50, 60} };
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of maximum size chain is %d\n",
maxChainLength( arr, n ));
return 0;
}
Java
class Pair{
int a;
int b;
231
Chapter 20. DP-20 | Maximum Length Chain of Pairs
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
// This function assumes that arr[] is sorted in increasing order
// according the first (or smaller) values in pairs.
static int maxChainLength(Pair arr[], int n)
{
int i, j, max = 0;
int mcl[] = new int[n];
/* Initialize MCL (max chain length) values for all indexes */
for ( i = 0; i < n; i++ )
mcl[i] = 1;
/* Compute optimized chain length values in bottom up manner */
for ( i = 1; i < n; i++ )
for ( j = 0; j < i; j++ )
if ( arr[i].a > arr[j].b && mcl[i] < mcl[j] + 1)
mcl[i] = mcl[j] + 1;
// mcl[i] now stores the maximum chain length ending with pair i
/* Pick maximum of all MCL values */
for ( i = 0; i < n; i++ )
if ( max < mcl[i] )
max = mcl[i];
return max;
}
/* Driver program to test above function */
public static void main(String[] args)
{
Pair arr[] = new Pair[] {new Pair(5,24), new Pair(15, 25),
new Pair (27, 40), new Pair(50, 60)};
System.out.println("Length of maximum size chain is " +
maxChainLength(arr, arr.length));
}
}
Python3
class Pair(object):
def __init__(self, a, b):
self.a = a
232
Chapter 20. DP-20 | Maximum Length Chain of Pairs
self.b = b
# This function assumes that arr[] is sorted in increasing
# order according the first (or smaller) values in pairs.
def maxChainLength(arr, n):
max = 0
# Initialize MCL(max chain length) values for all indices
mcl = [1 for i in range(n)]
# Compute optimized chain length values in bottom up manner
for i in range(1, n):
for j in range(0, i):
if (arr[i].a > arr[j].b and mcl[i] < mcl[j] + 1):
mcl[i] = mcl[j] + 1
# mcl[i] now stores the maximum
# chain length ending with pair i
# Pick maximum of all MCL values
for i in range(n):
if (max < mcl[i]):
max = mcl[i]
return max
# Driver program to test above function
arr = [Pair(5, 24), Pair(15, 25), Pair(27, 40), Pair(50, 60)]
print('Length of maximum size chain is',
maxChainLength(arr, len(arr)))
# This code is contributed by Soumen Ghosh
C#
233
Chapter 20. DP-20 | Maximum Length Chain of Pairs
this.b = b;
}
// This function assumes that arr[]
// is sorted in increasing order
// according the first (or smaller)
// values in pairs.
static int maxChainLength(Pair []arr, int n)
{
int i, j, max = 0;
int []mcl = new int[n];
// Initialize MCL (max chain length)
// values for all indexes
for(i = 0; i < n; i++ )
mcl[i] = 1;
// Compute optimized chain length
// values in bottom up manner
for(i = 1; i < n; i++)
for (j = 0; j < i; j++)
if(arr[i].a > arr[j].b &&
mcl[i] < mcl[j] + 1)
// mcl[i] now stores the maximum
// chain length ending with pair i
mcl[i] = mcl[j] + 1;
// Pick maximum of all MCL values
for ( i = 0; i < n; i++ )
if (max < mcl[i] )
max = mcl[i];
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));
}
}
// This code is contributed by nitin mittal.
234
Chapter 20. DP-20 | Maximum Length Chain of Pairs
Output:
Source
https://www.geeksforgeeks.org/maximum-length-chain-of-pairs-dp-20/
235
Chapter 21
8 1 4 3 5 2 6 7
--------------------------------------------
--------------------------------------------
1 2 3 4 5 6 7 8
Source:Dynamic Programming Practice Problems. The link also has well explained solution
for the problem.
2. Maximum Sum Increasing Subsequence: Given an array of n positive integers.
Write a program to find the maximum sum subsequence of the given array such that the
intgers in the subsequence are sorted in increasing order. For example, if input is {1, 101, 2,
3, 100, 4, 5}, then output should be {1, 2, 3, 100}. The solution to this problem has been
published here.
3. The Longest Chain You are given pairs of numbers. In a pair, the first number is
smaller with respect to the second number. Suppose you have two sets (a, b) and (c, d),
236
Chapter 21. DP-21 | Variations of LIS
the second set can follow the first set if b < c. So you can form a long chain in the similar
fashion. Find the longest chain which can be formed. The solution to this problem has been
published here.
4. Box Stacking You are given a set of n types of rectangular 3-D boxes, where the i^th
box has height h(i), width w(i) and depth d(i) (all real numbers). You want to create a
stack of boxes which is as tall as possible, but you can only stack a box on top of another
box if the dimensions of the 2-D base of the lower box are each strictly larger than those of
the 2-D base of the higher box. Of course, you can rotate a box so that any side functions
as its base. It is also allowable to use multiple instances of the same type of box.
Source:Dynamic Programming Practice Problems. The link also has well explained solution
for the problem.
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/variations-of-lis-dp-21/
237
Chapter 22
238
Chapter 22. DP-22 | Box Stacking Problem
The Box Stacking problem is a variation of LIS problem. We need to build a maximum
height stack.
Following are the key points to note in the problem statement:
1) A box can be placed on top of another box only if both width and depth of the upper
placed box are smaller than width and depth of the lower box respectively.
2) We can rotate boxes such that width is smaller than depth. For example, if there is a box
with dimensions {1x2x3} where 1 is height, 2×3 is base, then there can be three possibilities,
{1x2x3}, {2x1x3} and {3x1x2}
3) We can use multiple instances of boxes. What it means is, we can have two different
rotations of a box as part of our maximum height stack.
239
Chapter 22. DP-22 | Box Stacking Problem
C++
240
Chapter 22. DP-22 | Box Stacking Problem
241
Chapter 22. DP-22 | Box Stacking Problem
Java
242
Chapter 22. DP-22 | Box Stacking Problem
/*Constructor to initialise object*/
public Box(int h, int w, int d) {
this.h = h;
this.w = w;
this.d = d;
}
/*To sort the box array on the basis
of area in decreasing order of area */
@Override
public int compareTo(Box o) {
return o.area-this.area;
}
}
/* Returns the height of the tallest
stack that can be formed with give
type of boxes */
static int maxStackHeight( Box arr[], int n){
Box[] rot = new Box[n*3];
/* New Array of boxes is created -
considering all 3 possible rotations,
with width always greater than equal
to width */
for(int i = 0;i < n;i++){
Box box = arr[i];
/* Orignal Box*/
rot[3*i] = new Box(box.h, Math.max(box.w,box.d),
Math.min(box.w,box.d));
/* First rotation of box*/
rot[3*i + 1] = new Box(box.w, Math.max(box.h,box.d),
Math.min(box.h,box.d));
/* Second rotation of box*/
rot[3*i + 2] = new Box(box.d, Math.max(box.w,box.h),
Math.min(box.w,box.h));
}
/* Calculating base area of
each of the boxes.*/
for(int i = 0; i < rot.length; i++)
rot[i].area = rot[i].w * rot[i].d;
243
Chapter 22. DP-22 | Box Stacking Problem
244
Chapter 22. DP-22 | Box Stacking Problem
System.out.println("The maximum possible "+
"height of stack is " +
maxStackHeight(arr,4));
}
}
// This code is contributed by Divyam
Output:
In the above program, given input boxes are {4, 6, 7}, {1, 2, 3}, {4, 5, 6}, {10, 12, 32}.
Following are all rotations of the boxes in decreasing order of base area.
10 x 12 x 32
12 x 10 x 32
32 x 10 x 12
4 x 6 x 7
4 x 5 x 6
6 x 4 x 7
5 x 4 x 6
7 x 4 x 6
6 x 4 x 5
1 x 2 x 3
2 x 1 x 3
3 x 1 x 2
The height 60 is obtained by boxes { {3, 1, 2}, {1, 2, 3}, {6, 4, 5}, {4, 5, 6}, {4, 6, 7}, {32,
10, 12}, {10, 12, 32}}
Time Complexity: O(n^2)
Auxiliary Space: O(n)
Source
https://www.geeksforgeeks.org/box-stacking-problem-dp-22/
245
Chapter 23
DP-23 | Bellman–Ford
Algorithm
246
Chapter 23. DP-23 | Bellman–Ford Algorithm
How does this work? Like other Dynamic Programming Problems, the algorithm calcu-
late shortest paths in bottom-up manner. It first calculates the shortest distances which
have at-most one edge in the path. Then, it calculates shortest paths with at-most 2 edges,
and so on. After the i-th iteration of outer loop, the shortest paths with at most i edges
are calculated. There can be maximum |V| – 1 edges in any simple path, that is why the
outer loop runs |v| – 1 times. The idea is, assuming that there is no negative weight cycle,
if we have calculated shortest paths with at most i edges, then an iteration over all edges
guarantees to give shortest path with at-most (i+1) edges (Proof is simple, you can refer
this or MIT Video Lecture)
Example
Let us understand the algorithm with following example graph. The images are taken from
thissource.
Let the given source vertex be 0. Initialize all distances as infinite, except the distance to
source itself. Total number of vertices in the graph is 5, so all edges must be processed 4
times.
Let all edges are processed in following order: (B,E), (D,B), (B,D), (A,B), (A,C), (D,C),
(B,C), (E,D). We get following distances when all edges are processed first time. The first
row in shows initial distances. The second row shows distances when edges (B,E), (D,B),
(B,D) and (A,B) are processed. The third row shows distances when (A,C) is processed.
The fourth row shows when (D,C), (B,C) and (E,D) are processed.
247
Chapter 23. DP-23 | Bellman–Ford Algorithm
The first iteration guarantees to give all shortest paths which are at most 1 edge long. We
get following distances when all edges are processed second time (The last row shows final
values).
The second iteration guarantees to give all shortest paths which are at most 2 edges long.
The algorithm processes all edges 2 more times. The distances are minimized after the
second iteration, so third and fourth iterations don’t update the distances.
Implementation:
C++
248
Chapter 23. DP-23 | Bellman–Ford Algorithm
249
Chapter 23. DP-23 | Bellman–Ford Algorithm
250
Chapter 23. DP-23 | Bellman–Ford Algorithm
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = -1;
// add edge 0-2 (or A-C in above figure)
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 4;
// add edge 1-2 (or B-C in above figure)
graph->edge[2].src = 1;
graph->edge[2].dest = 2;
graph->edge[2].weight = 3;
// add edge 1-3 (or B-D in above figure)
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 2;
// add edge 1-4 (or A-E in above figure)
graph->edge[4].src = 1;
graph->edge[4].dest = 4;
graph->edge[4].weight = 2;
// add edge 3-2 (or D-C in above figure)
graph->edge[5].src = 3;
graph->edge[5].dest = 2;
graph->edge[5].weight = 5;
// add edge 3-1 (or D-B in above figure)
graph->edge[6].src = 3;
graph->edge[6].dest = 1;
graph->edge[6].weight = 1;
// add edge 4-3 (or E-D in above figure)
graph->edge[7].src = 4;
graph->edge[7].dest = 3;
graph->edge[7].weight = -3;
BellmanFord(graph, 0);
return 0;
}
Java
251
Chapter 23. DP-23 | Bellman–Ford Algorithm
import java.util.*;
import java.lang.*;
import java.io.*;
// A class to represent a connected, directed and weighted graph
class Graph
{
// A class to represent a weighted edge in graph
class Edge {
int src, dest, weight;
Edge() {
src = dest = weight = 0;
}
};
int V, E;
Edge edge[];
// Creates a graph with V vertices and E edges
Graph(int v, int e)
{
V = v;
E = e;
edge = new Edge[e];
for (int i=0; i<e; ++i)
edge[i] = new Edge();
}
// The main function that finds shortest distances from src
// to all other vertices using Bellman-Ford algorithm. The
// function also detects negative weight cycle
void BellmanFord(Graph graph,int src)
{
int V = graph.V, E = graph.E;
int dist[] = new int[V];
// Step 1: Initialize distances from src to all other
// vertices as INFINITE
for (int i=0; i<V; ++i)
dist[i] = Integer.MAX_VALUE;
dist[src] = 0;
// Step 2: Relax all edges |V| - 1 times. A simple
// shortest path from src to any other vertex can
// have at-most |V| - 1 edges
for (int i=1; i<V; ++i)
{
for (int j=0; j<E; ++j)
252
Chapter 23. DP-23 | Bellman–Ford Algorithm
{
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u]!=Integer.MAX_VALUE &&
dist[u]+weight<dist[v])
dist[v]=dist[u]+weight;
}
}
// Step 3: check for negative-weight cycles. The above
// step guarantees shortest distances if graph doesn't
// contain negative weight cycle. If we get a shorter
// path, then there is a cycle.
for (int j=0; j<E; ++j)
{
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE &&
dist[u]+weight < dist[v])
System.out.println("Graph contains negative weight cycle");
}
printArr(dist, V);
}
// A utility function used to print the solution
void printArr(int dist[], int V)
{
System.out.println("Vertex Distance from Source");
for (int i=0; i<V; ++i)
System.out.println(i+"\t\t"+dist[i]);
}
// Driver method to test above function
public static void main(String[] args)
{
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
Graph graph = new Graph(V, E);
// add edge 0-1 (or A-B in above figure)
graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = -1;
// add edge 0-2 (or A-C in above figure)
253
Chapter 23. DP-23 | Bellman–Ford Algorithm
graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 4;
// add edge 1-2 (or B-C in above figure)
graph.edge[2].src = 1;
graph.edge[2].dest = 2;
graph.edge[2].weight = 3;
// add edge 1-3 (or B-D in above figure)
graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 2;
// add edge 1-4 (or A-E in above figure)
graph.edge[4].src = 1;
graph.edge[4].dest = 4;
graph.edge[4].weight = 2;
// add edge 3-2 (or D-C in above figure)
graph.edge[5].src = 3;
graph.edge[5].dest = 2;
graph.edge[5].weight = 5;
// add edge 3-1 (or D-B in above figure)
graph.edge[6].src = 3;
graph.edge[6].dest = 1;
graph.edge[6].weight = 1;
// add edge 4-3 (or E-D in above figure)
graph.edge[7].src = 4;
graph.edge[7].dest = 3;
graph.edge[7].weight = -3;
graph.BellmanFord(graph, 0);
}
}
// Contributed by Aakash Hasija
Python
254
Chapter 23. DP-23 | Bellman–Ford Algorithm
def __init__(self,vertices):
self.V= vertices #No. of vertices
self.graph = [] # default dictionary to store graph
# function to add an edge to graph
def addEdge(self,u,v,w):
self.graph.append([u, v, w])
# utility function used to print the solution
def printArr(self, dist):
print("Vertex Distance from Source")
for i in range(self.V):
print("%d \t\t %d" % (i, dist[i]))
# The main function that finds shortest distances from src to
# all other vertices using Bellman-Ford algorithm. The function
# also detects negative weight cycle
def BellmanFord(self, src):
# Step 1: Initialize distances from src to all other vertices
# as INFINITE
dist = [float("Inf")] * self.V
dist[src] = 0
# Step 2: Relax all edges |V| - 1 times. A simple shortest
# path from src to any other vertex can have at-most |V| - 1
# edges
for i in range(self.V - 1):
# Update dist value and parent index of the adjacent vertices of
# the picked vertex. Consider only those vertices which are still in
# queue
for u, v, w in self.graph:
if dist[u] != float("Inf") and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
# Step 3: check for negative-weight cycles. The above step
# guarantees shortest distances if graph doesn't contain
# negative weight cycle. If we get a shorter path, then there
# is a cycle.
for u, v, w in self.graph:
if dist[u] != float("Inf") and dist[u] + w < dist[v]:
print "Graph contains negative weight cycle"
return
# print all distance
255
Chapter 23. DP-23 | Bellman–Ford Algorithm
self.printArr(dist)
g = Graph(5)
g.addEdge(0, 1, -1)
g.addEdge(0, 2, 4)
g.addEdge(1, 2, 3)
g.addEdge(1, 3, 2)
g.addEdge(1, 4, 2)
g.addEdge(3, 2, 5)
g.addEdge(3, 1, 1)
g.addEdge(4, 3, -3)
#Print the solution
g.BellmanFord(0)
#This code is contributed by Neelam Yadav
Output:
Notes
1) Negative weights are found in various applications of graphs. For example, instead of
paying cost for a path, we may get some advantage if we follow the path.
2) Bellman-Ford works better (better than Dijksra’s) for distributed systems. Unlike Di-
jksra’s where we need to find minimum value of all vertices, in Bellman-Ford, edges are
considered one by one.
Exercise
1) The standard Bellman-Ford algorithm reports shortest path only if there is no negative
weight cycles. Modify it so that it reports minimum distances even if there is a negative
weight cycle.
2) Can we use Dijksra’s algorithm for shortest paths for graphs with negative weights – one
idea can be, calculate the minimum weight value, add a positive value (equal to absolute
value of minimum weight value) to all weights and run the Dijksra’s algorithm for the
modified graph. Will this algorithm work?
References:
http://www.youtube.com/watch?v=Ttezuzs39nk
http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm
http://www.cs.arizona.edu/classes/cs445/spring07/ShortestPath2.prn.pdf
256
Chapter 23. DP-23 | Bellman–Ford Algorithm
Source
https://www.geeksforgeeks.org/bellman-ford-algorithm-dp-23/
257
Chapter 24
Example 1
Input: keys[] = {10, 12}, freq[] = {34, 50}
There can be following two possible BSTs
10 12
\ /
12 10
I II
Frequency of searches of 10 and 12 are 34 and 50 respectively.
The cost of tree I is 34*1 + 50*2 = 134
The cost of tree II is 50*1 + 34*2 = 118
Example 2
Input: keys[] = {10, 12, 20}, freq[] = {34, 8, 50}
There can be following possible BSTs
10 12 20 10 20
\ / \ / \ /
12 10 20 12 20 10
\ / / \
20 10 12 12
I II III IV V
258
Chapter 24. DP-24 | Optimal Binary Search Tree
1) Optimal Substructure:
The optimal cost for freq[i..j] can be recursively calculated using following formula.
C/C++
259
Chapter 24. DP-24 | Optimal Binary Search Tree
Java
260
Chapter 24. DP-24 | Optimal Binary Search Tree
261
Chapter 24. DP-24 | Optimal Binary Search Tree
C#
262
Chapter 24. DP-24 | Optimal Binary Search Tree
263
Chapter 24. DP-24 | Optimal Binary Search Tree
Output:
Time complexity of the above naive recursive approach is exponential. It should be noted
that the above function computes the same subproblems again and again. We can see many
subproblems being repeated in the following recursion tree for freq[1..4].
Since same suproblems are called again, this problem has Overlapping Subprolems property.
So optimal BST problem has both properties (see thisand this) of a dynamic programming
problem. Like other typical Dynamic Programming(DP) problems, recomputations of same
subproblems can be avoided by constructing a temporary array cost[][] in bottom up manner.
Dynamic Programming Solution
Following is C/C++ implementation for optimal BST problem using Dynamic Programming.
We use an auxiliary array cost[n][n] to store the solutions of subproblems. cost[0][n-1] will
hold the final result. The challenge in implementation is, all diagonal values must be filled
first, then the values which lie on the line just above the diagonal. In other words, we must
first fill all cost[i][i] values, then all cost[i][i+1] values, then all cost[i][i+2] values. So how to
fill the 2D array in such manner> The idea used in the implementation is same as Matrix
Chain Multiplication problem, we use a variable ‘L’ for chain length and increment ‘L’, one
by one. We calculate column number ‘j’ using the values of ‘i’ and ‘L’.
C/C++
264
Chapter 24. DP-24 | Optimal Binary Search Tree
#include <limits.h>
// A utility function to get sum of array elements
// freq[i] to freq[j]
int sum(int freq[], int i, int j);
/* A Dynamic Programming based function that calculates
minimum cost of a Binary Search Tree. */
int optimalSearchTree(int keys[], int freq[], int n)
{
/* Create an auxiliary 2D matrix to store results
of subproblems */
int cost[n][n];
/* cost[i][j] = Optimal cost of binary search tree
that can be formed from keys[i] to keys[j].
cost[0][n-1] will store the resultant cost */
// For a single key, cost is equal to frequency of the key
for (int i = 0; i < n; i++)
cost[i][i] = freq[i];
// Now we need to consider chains of length 2, 3, ... .
// L is chain length.
for (int L=2; L<=n; L++)
{
// i is row number in cost[][]
for (int i=0; i<=n-L+1; i++)
{
// Get column number j from row number i and
// chain length L
int j = i+L-1;
cost[i][j] = INT_MAX;
// Try making all keys in interval keys[i..j] as root
for (int r=i; r<=j; r++)
{
// c = cost when keys[r] becomes root of this subtree
int c = ((r > i)? cost[i][r-1]:0) +
((r < j)? cost[r+1][j]:0) +
sum(freq, i, j);
if (c < cost[i][j])
cost[i][j] = c;
}
}
}
return cost[0][n-1];
}
265
Chapter 24. DP-24 | Optimal Binary Search Tree
// A utility function to get sum of array elements
// freq[i] to freq[j]
int sum(int freq[], int i, int j)
{
int s = 0;
for (int k = i; k <=j; k++)
s += freq[k];
return s;
}
// Driver program to test above functions
int main()
{
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = sizeof(keys)/sizeof(keys[0]);
printf("Cost of Optimal BST is %d ",
optimalSearchTree(keys, freq, n));
return 0;
}
Java
266
Chapter 24. DP-24 | Optimal Binary Search Tree
C#
267
Chapter 24. DP-24 | Optimal Binary Search Tree
268
Chapter 24. DP-24 | Optimal Binary Search Tree
Output:
Notes
1) The time complexity of the above solution is O(n^4). The time complexity can be easily
reduced to O(n^3) by pre-calculating sum of frequencies instead of calling sum() again and
again.
2) In the above solutions, we have computed optimal cost only. The solutions can be easily
modified to store the structure of BSTs also. We can create another auxiliary array of size
n to store the structure of tree. All we need to do is, store the chosen ‘r’ in the innermost
loop.
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.
Improved By : aradhya95
Source
https://www.geeksforgeeks.org/optimal-binary-search-tree-dp-24/
269
Chapter 25
Let isSubSetSum(int set[], int n, int sum) be the function to find whether there is a subset
of set[] with sum equal to sum. n is the number of elements in set[].
The isSubsetSum problem can be divided into two subproblems
…a) Include the last element, recur for n = n-1, sum = sum – set[n-1]
…b) Exclude the last element, recur for n = n-1.
If any of the above the above subproblems return true, then return true.
Following is the recursive formula for isSubsetSum() problem.
270
Chapter 25. DP-25 | Subset Sum Problem
Following is naive recursive implementation that simply follows the recursive structure
mentioned above.
271
Chapter 25. DP-25 | Subset Sum Problem
Java
272
Chapter 25. DP-25 | Subset Sum Problem
Python3
C#
273
Chapter 25. DP-25 | Subset Sum Problem
using System;
class GFG
{
// Returns true if there is a subset of set[] with sum
// equal to given sum
static bool isSubsetSum(int []set, int n, int sum)
{
// Base Cases
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
// If last element is greater than sum,
// then ignore it
if (set[n-1] > sum)
return isSubsetSum(set, n-1, sum);
/* else, check if sum can be obtained
by any of the following
(a) including the last element
(b) excluding the last element */
return isSubsetSum(set, n-1, sum) ||
isSubsetSum(set, n-1, sum-set[n-1]);
}
// Driver program
public static void Main ()
{
int []set = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = set.Length;
if (isSubsetSum(set, n, sum) == true)
Console.WriteLine("Found a subset with given sum");
else
Console.WriteLine("No subset with given sum");
}
}
// This code is contributed by Sam007
PHP
<?php
// A recursive solution for subset sum problem
// Returns true if there is a subset of set
274
Chapter 25. DP-25 | Subset Sum Problem
Output:
The above solution may try all subsets of given set in worst case. Therefore time complexity
of the above solution is exponential. The problem is in-fact NP-Complete (There is no
known polynomial time solution for this problem).
We can solve the problem in Pseudo-polynomial time using Dynamic program-
ming. We create a boolean 2D table subset[][] and fill it in bottom up manner. The value
of subset[i][j] will be true if there is a subset of set[0..j-1] with sum equal to i., otherwise
275
Chapter 25. DP-25 | Subset Sum Problem
276
Chapter 25. DP-25 | Subset Sum Problem
{
int set[] = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = sizeof(set)/sizeof(set[0]);
if (isSubsetSum(set, n, sum) == true)
printf("Found a subset with given sum");
else
printf("No subset with given sum");
return 0;
}
// This code is contributed by Arjun Tyagi.
Java
277
Chapter 25. DP-25 | Subset Sum Problem
}
}
/* // uncomment this code to print table
for (int i = 0; i <= sum; i++)
{
for (int j = 0; j <= n; j++)
System.out.println (subset[i][j]);
} */
return subset[sum][n];
}
/* Driver program to test above function */
public static void main (String args[])
{
int set[] = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = set.length;
if (isSubsetSum(set, n, sum) == true)
System.out.println("Found a subset"
+ " with given sum");
else
System.out.println("No subset with"
+ " given sum");
}
}
/* This code is contributed by Rajat Mishra */
C#
278
Chapter 25. DP-25 | Subset Sum Problem
// If sum is not 0 and set is empty, then answer is false
for (int i = 1; i <= sum; i++)
subset[i, 0] = false;
// Fill the subset table in botton up manner
for (int i = 1; i <= sum; i++)
{
for (int j = 1; j <= n; j++)
{
subset[i, j] = subset[i, j - 1];
if (i >= set[j - 1])
subset[i, j] = subset[i, j] ||
subset[i - set[j - 1], j - 1];
}
}
return subset[sum,n];
}
// Driver program
public static void Main ()
{
int []set = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = set.Length;
if (isSubsetSum(set, n, sum) == true)
Console.WriteLine("Found a subset with given sum");
else
Console.WriteLine("No subset with given sum");
}
}
// This code is contributed by Sam007
PHP
<?php
// A Dynamic Programming solution for
// subset sum problem
// Returns true if there is a subset of
// set[] with sun equal to given sum
function isSubsetSum( $set, $n, $sum)
{
// The value of subset[i][j] will
// be true if there is a subset of
// set[0..j-1] with sum equal to i
279
Chapter 25. DP-25 | Subset Sum Problem
$subset = array(array());
// If sum is 0, then answer is true
for ( $i = 0; $i <= $n; $i++)
$subset[$i][0] = true;
// If sum is not 0 and set is empty,
// then answer is false
for ( $i = 1; $i <= $sum; $i++)
$subset[0][$i] = false;
// Fill the subset table in botton
// up manner
for ($i = 1; $i <= $n; $i++)
{
for ($j = 1; $j <= $sum; $j++)
{
if($j < $set[$i-1])
$subset[$i][$j] =
$subset[$i-1][$j];
if ($j >= $set[$i-1])
$subset[$i][$j] =
$subset[$i-1][$j] ||
$subset[$i - 1][$j -
$set[$i-1]];
}
}
/* // uncomment this code to print table
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= sum; j++)
printf ("%4d", subset[i][j]);
printf("n");
}*/
return $subset[$n][$sum];
}
// Driver program to test above function
$set = array(3, 34, 4, 12, 5, 2);
$sum = 9;
$n = count($set);
if (isSubsetSum($set, $n, $sum) == true)
echo "Found a subset with given sum";
else
echo "No subset with given sum";
280
Chapter 25. DP-25 | Subset Sum Problem
// This code is contributed by anuj_67.
?>
Output:
Time complexity of the above solution is O(sum*n).Subset Sum Problem in O(sum) space
Perfect Sum Problem (Print all subsets with given sum)
Improved By : vt_m
Source
https://www.geeksforgeeks.org/subset-sum-problem-dp-25/
281
Chapter 26
282
Chapter 26. DP-26 | Largest Independent Set Problem
The idea is simple, there are two possibilities for every node X, either X is a member of
the set or not a member. If X is a member, then the value of LISS(X) is 1 plus LISS of all
grandchildren. If X is not a member, then the value is sum of LISS of all children.
2) Overlapping Subproblems
Following is recursive implementation that simply follows the recursive structure mentioned
above.
283
Chapter 26. DP-26 | Largest Independent Set Problem
// A utility function to create a node
struct node* newNode( int data )
{
struct node* temp = (struct node *) malloc( sizeof(struct node) );
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us construct the tree given in the above diagram
struct node *root = newNode(20);
root->left = newNode(8);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
root->right = newNode(22);
root->right->right = newNode(25);
printf ("Size of the Largest Independent Set is %d ", LISS(root));
return 0;
}
Output:
Time complexity of the above naive recursive approach is exponential. It should be noted
that the above function computes the same subproblems again and again. For example,
LISS of node with value 50 is evaluated for node with values 10 and 20 as 50 is grandchild
of 10 and child of 20.
Since same suproblems are called again, this problem has Overlapping Subprolems prop-
erty. So LISS problem has both properties (see thisand this) of a dynamic programming
problem. Like other typical Dynamic Programming(DP) problems, recomputations of same
subproblems can be avoided by storing the solutions to subproblems and solving problems
in bottom up manner.
Following is C implementation of Dynamic Programming based solution. In the following
solution, an additional field ‘liss’ is added to tree nodes. The initial value of ‘liss’ is set as
0 for all nodes. The recursive function LISS() calculates ‘liss’ for a node only if it is not
already set.
C
284
Chapter 26. DP-26 | Largest Independent Set Problem
285
Chapter 26. DP-26 | Largest Independent Set Problem
Java
286
Chapter 26. DP-26 | Largest Independent Set Problem
287
Chapter 26. DP-26 | Largest Independent Set Problem
// This code is contributed by Rishabh Mahrsee
Output
Time Complexity: O(n) where n is the number of nodes in given Binary tree.
Following extensions to above solution can be tried as an exercise.
1) Extend the above solution for n-ary tree.
2) The above solution modifies the given tree structure by adding an additional field ‘liss’
to tree nodes. Extend the solution so that it doesn’t modify the tree structure.
3) The above solution only returns size of LIS, it doesn’t print elements of LIS. Extend the
solution to print all nodes that are part of LIS.
Source
https://www.geeksforgeeks.org/largest-independent-set-problem-dp-26/
288
Chapter 27
This problem is mainly an extension of Largest Sum Contiguous Subarray for 1D array.
The naive solution for this problem is to check every possible rectangle in given 2D array.
This solution requires 4 nested loops and time complexity of this solution would be O(n^4).
Kadane’s algorithm for 1D array can be used to reduce the time complexity to O(n^3).
The idea is to fix the left and right columns one by one and find the maximum sum
contiguous rows for every left and right column pair. We basically find top and bottom row
numbers (which have maximum sum) for every fixed left and right column pair. To find
the top and bottom row numbers, calculate sun of elements in every row from left to right
and store these sums in an array say temp[]. So temp[i] indicates sum of elements from left
289
Chapter 27. DP-27 | Maximum sum rectangle in a 2D matrix
to right in row i. If we apply Kadane’s 1D algorithm on temp[], and get the maximum sum
subarray of temp, this maximum sum would be the maximum possible sum with left and
right as boundary columns. To get the overall maximum sum, we compare this sum with
the maximum sum so far.
290
Chapter 27. DP-27 | Maximum sum rectangle in a 2D matrix
// Special Case: When all numbers in arr[] are negative
maxSum = arr[0];
*start = *finish = 0;
// Find the maximum element in array
for (i = 1; i < n; i++)
{
if (arr[i] > maxSum)
{
maxSum = arr[i];
*start = *finish = i;
}
}
return maxSum;
}
// The main function that finds maximum sum rectangle in M[][]
void findMaxSum(int M[][COL])
{
// Variables to store the final output
int maxSum = INT_MIN, finalLeft, finalRight, finalTop, finalBottom;
int left, right, i;
int temp[ROW], sum, start, finish;
// Set the left column
for (left = 0; left < COL; ++left)
{
// Initialize all elements of temp as 0
memset(temp, 0, sizeof(temp));
// Set the right column for the left column set by outer loop
for (right = left; right < COL; ++right)
{
// Calculate sum between current left and right for every row 'i'
for (i = 0; i < ROW; ++i)
temp[i] += M[i][right];
// Find the maximum sum subarray in temp[]. The kadane()
// function also sets values of start and finish. So 'sum' is
// sum of rectangle between (start, left) and (finish, right)
// which is the maximum sum with boundary columns strictly as
// left and right.
sum = kadane(temp, &start, &finish, ROW);
// Compare sum with maximum sum so far. If sum is more, then
// update maxSum and other output values
291
Chapter 27. DP-27 | Maximum sum rectangle in a 2D matrix
Java
import java.util.*;
import java.lang.*;
import java.io.*;
/**
* Given a 2D array, find the maximum sum subarray in it
*/
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
findMaxSubMatrix(new int[][] {
{1, 2, -1, -4, -20},
{-8, -3, 4, 2, 1},
{3, 8, 10, 1, 3},
292
Chapter 27. DP-27 | Maximum sum rectangle in a 2D matrix
293
Chapter 27. DP-27 | Maximum sum rectangle in a 2D matrix
int[] currentResult;
int maxSum = Integer.MIN_VALUE;
int left = 0;
int top = 0;
int right = 0;
int bottom = 0;
for (int leftCol = 0; leftCol < cols; leftCol++) {
int[] tmp = new int[rows];
for (int rightCol = leftCol; rightCol < cols; rightCol++) {
for (int i = 0; i < rows; i++) {
tmp[i] += a[i][rightCol];
}
currentResult = kadane(tmp);
if (currentResult[0] > maxSum) {
maxSum = currentResult[0];
left = leftCol;
top = currentResult[1];
right = rightCol;
bottom = currentResult[2];
}
}
}
System.out.println("MaxSum: " + maxSum +
", range: [(" + left + ", " + top +
")(" + right + ", " + bottom + ")]");
}
}
// Thanks to Ilia Savin for contributing this code.
Output:
294
Chapter 27. DP-27 | Maximum sum rectangle in a 2D matrix
Source
https://www.geeksforgeeks.org/maximum-sum-rectangle-in-a-2d-matrix-dp-27/
295
Chapter 28
Let the input string be str[l……h]. The problem can be broken down into three parts:
1. Find the minimum number of insertions in the substring str[l+1,…….h].
2. Find the minimum number of insertions in the substring str[l…….h-1].
3. Find the minimum number of insertions in the substring str[l+1……h-1].
Recursive Solution
The minimum number of insertions in the string str[l…..h] can be given as:
296
Chapter 28. DP-28 | Minimum insertions to form a palindrome
// palindrome
#include <stdio.h>
#include <limits.h>
#include <string.h>
// A utility function to find minimum of two numbers
int min(int a, int b)
{ return a < b ? a : b; }
// Recursive function to find minimum number of
// insertions
int findMinInsertions(char str[], int l, int h)
{
// Base Cases
if (l > h) return INT_MAX;
if (l == h) return 0;
if (l == h - 1) return (str[l] == str[h])? 0 : 1;
// Check if the first and last characters are
// same. On the basis of the comparison result,
// decide which subrpoblem(s) to call
return (str[l] == str[h])?
findMinInsertions(str, l + 1, h - 1):
(min(findMinInsertions(str, l, h - 1),
findMinInsertions(str, l + 1, h)) + 1);
}
// Driver program to test above functions
int main()
{
char str[] = "geeks";
printf("%d", findMinInsertions(str, 0, strlen(str)-1));
return 0;
}
Java
297
Chapter 28. DP-28 | Minimum insertions to form a palindrome
C#
298
Chapter 28. DP-28 | Minimum insertions to form a palindrome
Output:
abcde
/ | \
/ | \
bcde abcd bcd <- case 3 is discarded as str[l] != str[h]
/ | \ / | \
/ | \ / | \
cde bcd cd bcd abc bc
/ | \ / | \ /|\ / | \
de cd d cd bc c………………….
The substrings in bold show that the recursion to be terminated and the recursion tree cannot
originate from there. Substring in the same color indicates overlapping subproblems.
How to reuse solutions of subproblems?
We can create a table to store results of subproblems so that they can be used directly if
same subproblem is encountered again.
The below table represents the stored values for the string abcde.
299
Chapter 28. DP-28 | Minimum insertions to form a palindrome
a b c d e
----------
0 1 2 3 4
0 0 1 2 3
0 0 0 1 2
0 0 0 0 1
0 0 0 0 0
Gap = 1:
(0, 1) (1, 2) (2, 3) (3, 4)
Gap = 2:
(0, 2) (1, 3) (2, 4)
Gap = 3:
(0, 3) (1, 4)
Gap = 4:
(0, 4)
300
Chapter 28. DP-28 | Minimum insertions to form a palindrome
// Fill the table
for (gap = 1; gap < n; ++gap)
for (l = 0, h = gap; h < n; ++l, ++h)
table[l][h] = (str[l] == str[h])?
table[l+1][h-1] :
(min(table[l][h-1],
table[l+1][h]) + 1);
// Return minimum number of insertions for
// str[0..n-1]
return table[0][n-1];
}
// Driver program to test above function.
int main()
{
char str[] = "geeks";
printf("%d", findMinInsertionsDP(str, strlen(str)));
return 0;
}
Java
301
Chapter 28. DP-28 | Minimum insertions to form a palindrome
table[l+1][h]) + 1);
// Return minimum number of insertions
// for str[0..n-1]
return table[0][n-1];
}
// Driver program to test above function.
public static void main(String args[])
{
String str = "geeks";
System.out.println(
findMinInsertionsDP(str.toCharArray(), str.length()));
}
}
// This code is contributed by Sumit Ghosh
Output:
302
Chapter 28. DP-28 | Minimum insertions to form a palindrome
{
int L[n+1][n+1];
int i, j;
/* Following steps build L[m+1][n+1] in bottom
up fashion. Note that L[i][j] contains length
of LCS of X[0..i-1] and Y[0..j-1] */
for (i=0; i<=m; i++)
{
for (j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
/* L[m][n] contains length of LCS for X[0..n-1]
and Y[0..m-1] */
return L[m][n];
}
// LCS based function to find minimum number of
// insertions
int findMinInsertionsLCS(char str[], int n)
{
// Creata another string to store reverse of 'str'
char rev[n+1];
strcpy(rev, str);
strrev(rev);
// The output is length of string minus length of lcs of
// str and it reverse
return (n - lcs(str, rev, n, n));
}
// Driver program to test above functions
int main()
{
char str[] = "geeks";
printf("%d", findMinInsertionsLCS(str, strlen(str)));
return 0;
}
303
Chapter 28. DP-28 | Minimum insertions to form a palindrome
Java
304
Chapter 28. DP-28 | Minimum insertions to form a palindrome
Output:
Time complexity of this method is also O(n^2) and this method also requires O(n^2) extra
space.
Related Article :
Minimum number of Appends needed to make a string palindrome
This article is compiled by Aashish Barnwal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Sam007
Source
https://www.geeksforgeeks.org/minimum-insertions-to-form-a-palindrome-dp-28/
305
Chapter 29
306
Chapter 29. DP-29 | Longest Common Substring
The maximum length Longest Common Suffix is the longest common substring.
LCSubStr(X, Y, m, n) = Max(LCSuff(X, Y, i, j)) where 1 <= i <= m
and 1 <= j <= n
C++
307
Chapter 29. DP-29 | Longest Common Substring
308
Chapter 29. DP-29 | Longest Common Substring
return 0;
}
Java
309
Chapter 29. DP-29 | Longest Common Substring
int m = X.length();
int n = Y.length();
System.out.println("Length of Longest Common Substring is "
+ LCSubStr(X.toCharArray(), Y.toCharArray(), m, n));
}
}
// This code is contributed by Sumit Ghosh
Python3
310
Chapter 29. DP-29 | Longest Common Substring
# Driver Program to test above function
X = 'OldSite:GeeksforGeeks.org'
Y = 'NewSite:GeeksQuiz.com'
m = len(X)
n = len(Y)
print('Length of Longest Common Substring is',
LCSubStr(X, Y, m, n))
# This code is contributed by Soumen Ghosh
C#
311
Chapter 29. DP-29 | Longest Common Substring
LCStuff[i, j] =
LCStuff[i - 1, j - 1] + 1;
result = Math.Max(result,
LCStuff[i, j]);
}
else
LCStuff[i, j] = 0;
}
}
return result;
}
// Driver Program to test above function
public static void Main()
{
String X = "OldSite:GeeksforGeeks.org";
String Y = "NewSite:GeeksQuiz.com";
int m = X.Length;
int n = Y.Length;
Console.Write("Length of Longest Common"
+ " Substring is " + LCSubStr(X, Y, m, n));
}
}
// This code is contributed by Sam007.
Output:
Source
https://www.geeksforgeeks.org/longest-common-substring-dp-29/
312
Chapter 30
Why DP approach?
The above problem exhibits overlapping subproblems. See the below diagram. Also, see
thisrecursive implementation. Let there be 3 dice, each with 6 faces and we need to find the
number of ways to get sum 8:
313
Chapter 30. DP-30 | Dice Throw
Please take a closer look at the above recursion. The sub-problems in RED are solved
first time and sub-problems in BLUE are solved again (exhibit overlapping sub-problems).
Hence, storing the results of the solved sub-problems saves time.
Following is implementation of Dynamic Programming approach.
C++
// C++ program to find number of ways to get sum 'x' with 'n'
// dice where every dice has 'm' faces
#include <iostream>
#include <string.h>
using namespace std;
// The main function that returns number of ways to get sum 'x'
// with 'n' dice and 'm' with m faces.
int findWays(int m, int n, int x)
{
314
Chapter 30. DP-30 | Dice Throw
C#
315
Chapter 30. DP-30 | Dice Throw
class GFG
{
// The main function that returns
// number of ways to get sum 'x'
// with 'n' dice and 'm' with m faces.
static int findWays(int m,
int n, int x)
{
// Create a table to store
// results of subproblems.
// row and column are used
// for simpilicity (Number
// of dice is directly used
// as row index and sum is
// directly used as column
// index). The entries in 0th
// row and 0th column are
// never used.
int[,] table = new int[n + 1,
x + 1];
// Initialize all
// entries as 0
for (int i = 0; i <= n; i++)
for (int j = 0; j <= x; j++)
table[i, j] = 0;
// Table entries for
// only one dice
for (int j = 1;
j <= m && j <= x; j++)
table[1, j] = 1;
// Fill rest of the entries
// in table using recursive
// relation i: number of
// dice, j: sum
for (int i = 2; i <= n; i++)
for (int j = 1; j <= x; j++)
for (int k = 1;
k <= m && k < j; k++)
table[i, j] += table[i - 1,
j - k];
/* Uncomment these lines to
see content of table
for (int i = 0; i <= n; i++)
316
Chapter 30. DP-30 | Dice Throw
{
for (int j = 0; j <= x; j++)
cout << table[i][j] << " ";
cout << endl;
} */
return table[n, x];
}
// Driver Code
public static void Main()
{
Console.WriteLine(findWays(4, 2, 1));
Console.WriteLine(findWays(2, 2, 3));
Console.WriteLine(findWays(6, 3, 8));
Console.WriteLine(findWays(4, 2, 5));
Console.WriteLine(findWays(4, 3, 5));
}
}
// This code is contributed by mits.
PHP
<?php
// PHP program to find number
// of ways to get sum 'x' with
// 'n' dice where every dice
// has 'm' faces
// The main function that returns
// number of ways to get sum 'x'
// with 'n' dice and 'm' with m faces.
function findWays($m, $n, $x)
{
// Create a table to store results
// of subproblems. One extra row
// and column are used for
// simpilicity (Number of dice is
// directly used as row index and
// sum is directly used as column
// index). The entries in 0th row
// and 0th column are never used.
$table;
// Initialize all entries as 0
for ($i = 1; $i < $n + 1; $i++)
for ($j = 1; $j < $x + 1; $j++)
$table[$i][$j] = 0;
317
Chapter 30. DP-30 | Dice Throw
// Table entries for
// only one dice
for ($j = 1; $j <= $m &&
$j <= $x; $j++)
$table[1][$j] = 1;
// Fill rest of the entries
// in table using recursive
// relation i: number of dice,
// j: sum
for ($i = 2; $i <= $n; $i++)
for ($j = 1; $j <= $x; $j++)
for ($k = 1; $k <= $m &&
$k < $j; $k++)
$table[$i][$j] +=
$table[$i - 1][$j - $k];
return $table[$n][$x];
}
// Driver Code
echo findWays(4, 2, 1). "\n";
echo findWays(2, 2, 3). "\n";
echo findWays(6, 3, 8). "\n";
echo findWays(4, 2, 5). "\n";
echo findWays(4, 3, 5). "\n";
// This code is contributed by mits.
?>
Output :
0
2
21
4
6
// When x is so high that sum can not go beyond x even when we
// get maximum value in every dice throw.
318
Chapter 30. DP-30 | Dice Throw
if (m*n <= x)
return (m*n == x);
// When x is too low
if (n >= x)
return (n == x);
With above conditions added, time complexity becomes O(1) when x >= m*n or when x
<= n.
Exercise:
Extend the above algorithm to find the probability to get Sum > X.
This article is compiled by Aashish Barnwal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Mithun Kumar
Source
https://www.geeksforgeeks.org/dice-throw-dp-30/
319
Chapter 31
320
Chapter 31. DP-31 | Optimal Strategy for a Game
So if the user follows the second game state, maximum value can be collected although the
first move is not the best.
There are two choices:
1. The user chooses the ith coin with value Vi: The opponent either chooses (i+1)th coin
or jth coin. The opponent intends to choose the coin which leaves the user with minimum
value.
i.e. The user can collect the value Vi + min(F(i+2, j), F(i+1, j-1) )
2. The user chooses the jth coin with value Vj: The opponent either chooses ith coin or
(j-1)th coin. The opponent intends to choose the coin which leaves the user with minimum
value.
i.e. The user can collect the value Vj + min(F(i+1, j-1), F(i, j-2) )
Following is recursive solution that is based on above two choices. We take the maximum
of two choices.
F(i, j) represents the maximum value the user can collect from
i'th coin to j'th coin.
321
Chapter 31. DP-31 | Optimal Strategy for a Game
calculated twice.
C++
322
Chapter 31. DP-31 | Optimal Strategy for a Game
Java
323
Chapter 31. DP-31 | Optimal Strategy for a Game
// Driver program
public static void main(String[] args)
{
int arr1[] = { 8, 15, 3, 7 };
int n = arr1.length;
System.out.println("" + optimalStrategyOfGame(arr1, n));
int arr2[] = { 2, 2, 2, 2 };
n = arr2.length;
System.out.println("" + optimalStrategyOfGame(arr2, n));
int arr3[] = { 20, 30, 2, 2, 2, 10 };
n = arr3.length;
System.out.println("" + optimalStrategyOfGame(arr3, n));
}
}
// This code is contributed by vt_m
Output:
22
4
42
Exercise
Your thoughts on the strategy when the user wishes to only win instead of winning with the
maximum value. Like above problem, number of coins is even.
Can Greedy approach work quite well and give an optimal solution? Will your answer
change if number of coins is odd? Please see Coin game of two corners
This article is compiled by Aashish Barnwal. 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/optimal-strategy-for-a-game-dp-31/
324
Chapter 32
Input: ilike
Output: Yes
The string can be segmented as "i like".
Input: ilikesamsung
Output: Yes
The string can be segmented as "i like samsung"
or "i like sam sung".
Recursive implementation:
The idea is simple, we consider each prefix and search it in dictionary. If the prefix is present
in dictionary, we recur for rest of the string (or suffix). If the recursive call for suffix returns
true, we return true, otherwise we try next prefix. If we have tried all prefixes and none of
them resulted in a solution, we return false.
We strongly recommend to see substrfunction which is used extensively in following imple-
mentations.
325
Chapter 32. DP-32 | Word Break Problem
// words in dictionary
#include <iostream>
using namespace std;
/* A utility function to check whether a word is
present in dictionary or not. An array of strings
is used for dictionary. Using array of strings for
dictionary is definitely not a good idea. We have
used for simplicity of the program*/
int dictionaryContains(string word)
{
string dictionary[] = {"mobile","samsung","sam","sung",
"man","mango","icecream","and",
"go","i","like","ice","cream"};
int size = sizeof(dictionary)/sizeof(dictionary[0]);
for (int i = 0; i < size; i++)
if (dictionary[i].compare(word) == 0)
return true;
return false;
}
// returns true if string can be segmented into space
// separated words, otherwise returns false
bool wordBreak(string str)
{
int size = str.size();
// Base case
if (size == 0) return true;
// Try all prefixes of lengths from 1 to size
for (int i=1; i<=size; i++)
{
// The parameter for dictionaryContains is
// str.substr(0, i) which is prefix (of input
// string) of length 'i'. We first check whether
// current prefix is in dictionary. Then we
// recursively check for remaining string
// str.substr(i, size-i) which is suffix of
// length size-i
if (dictionaryContains( str.substr(0, i) ) &&
wordBreak( str.substr(i, size-i) ))
return true;
}
// If we have tried all prefixes and
// none of them worked
return false;
326
Chapter 32. DP-32 | Word Break Problem
}
// Driver program to test above functions
int main()
{
wordBreak("ilikesamsung")? cout <<"Yes\n": cout << "No\n";
wordBreak("iiiiiiii")? cout <<"Yes\n": cout << "No\n";
wordBreak("")? cout <<"Yes\n": cout << "No\n";
wordBreak("ilikelikeimangoiii")? cout <<"Yes\n": cout << "No\n";
wordBreak("samsungandmango")? cout <<"Yes\n": cout << "No\n";
wordBreak("samsungandmangok")? cout <<"Yes\n": cout << "No\n";
return 0;
}
Output:
Yes
Yes
Yes
Yes
Yes
No
Dynamic Programming
Why Dynamic Programming? The above problem exhibits overlapping sub-problems. For
example, see the following partial recursion tree for string “abcde” in worst case.
327
Chapter 32. DP-32 | Word Break Problem
#include <iostream>
#include <string.h>
using namespace std;
/* A utility function to check whether a word is present in dictionary or not.
An array of strings is used for dictionary. Using array of strings for
dictionary is definitely not a good idea. We have used for simplicity of
the program*/
int dictionaryContains(string word)
{
string dictionary[] = {"mobile","samsung","sam","sung","man","mango",
"icecream","and","go","i","like","ice","cream"};
int size = sizeof(dictionary)/sizeof(dictionary[0]);
for (int i = 0; i < size; i++)
if (dictionary[i].compare(word) == 0)
return true;
return false;
}
// Returns true if string can be segmented into space separated
// words, otherwise returns false
bool wordBreak(string str)
{
int size = str.size();
if (size == 0) return true;
// Create the DP table to store results of subroblems. The value wb[i]
// will be true if str[0..i-1] can be segmented into dictionary words,
// otherwise false.
bool wb[size+1];
memset(wb, 0, sizeof(wb)); // Initialize all values as false.
for (int i=1; i<=size; i++)
{
// if wb[i] is false, then check if current prefix can make it true.
// Current prefix is "str.substr(0, i)"
if (wb[i] == false && dictionaryContains( str.substr(0, i) ))
wb[i] = true;
// wb[i] is true, then check for all substrings starting from
// (i+1)th character and store their results.
if (wb[i] == true)
{
// If we reached the last prefix
if (i == size)
return true;
for (int j = i+1; j <= size; j++)
328
Chapter 32. DP-32 | Word Break Problem
{
// Update wb[j] if it is false and can be updated
// Note the parameter passed to dictionaryContains() is
// substring starting from index 'i' and length 'j-i'
if (wb[j] == false && dictionaryContains( str.substr(i, j-i) ))
wb[j] = true;
// If we reached the last character
if (j == size && wb[j] == true)
return true;
}
}
}
/* Uncomment these lines to print DP table "wb[]"
for (int i = 1; i <= size; i++)
cout << " " << wb[i]; */
// If we have tried all prefixes and none of them worked
return false;
}
// Driver program to test above functions
int main()
{
wordBreak("ilikesamsung")? cout <<"Yes\n": cout << "No\n";
wordBreak("iiiiiiii")? cout <<"Yes\n": cout << "No\n";
wordBreak("")? cout <<"Yes\n": cout << "No\n";
wordBreak("ilikelikeimangoiii")? cout <<"Yes\n": cout << "No\n";
wordBreak("samsungandmango")? cout <<"Yes\n": cout << "No\n";
wordBreak("samsungandmangok")? cout <<"Yes\n": cout << "No\n";
return 0;
}
Output:
Yes
Yes
Yes
Yes
Yes
No
329
Chapter 32. DP-32 | Word Break Problem
In this program, we are using some extra space. However, its time complexity is O(n*s)
where s is the length of the largest string in the dictionary and n is the length of the given
string.
330
Chapter 32. DP-32 | Word Break Problem
for (int i = 0; i < n; i++) {
int msize = matched_index.size();
// Flag value which tells that a substring matches
// with given words or not.
int f = 0;
// Check all the substring from the indexes matched
// earlier. If any of that substring matches than
// make flag value = 1;
for (int j = msize - 1; j >= 0; j--) {
// sb is substring starting from matched_index[j]
// + 1 and of length i - matched_index[j]
string sb = s.substr(matched_index[j] + 1, i - matched_index[j]);
if (dictionaryContains(sb)) {
f = 1;
break;
}
}
// If substring matches than do dp[i] = 1 and
// push that index in matched_index array.
if (f == 1) {
dp[i] = 1;
matched_index.push_back(i);
}
}
return dp[n - 1];
}
// Driver code
int main()
{
wordBreak("ilikesamsung") ? cout << "Yes\n" : cout << "No\n";
wordBreak("iiiiiiii") ? cout << "Yes\n" : cout << "No\n";
wordBreak("") ? cout << "Yes\n" : cout << "No\n";
wordBreak("ilikelikeimangoiii") ? cout << "Yes\n" : cout << "No\n";
wordBreak("samsungandmango") ? cout << "Yes\n" : cout << "No\n";
wordBreak("samsungandmangok") ? cout << "Yes\n" : cout << "No\n";
return 0;
}
Output:
331
Chapter 32. DP-32 | Word Break Problem
Yes
Yes
Yes
Yes
Yes
No
Input: ilikeicecreamandmango
Output:
i like ice cream and man go
i like ice cream and mango
i like icecream and man go
i like icecream and mango
Input: ilikesamsungmobile
Output:
i like sam sung mobile
i like samsung mobile
Source
https://www.geeksforgeeks.org/word-break-problem-dp-32/
332
Chapter 33
333
Chapter 33. DP-33 | Find if a string is interleaved of two other strings
Dynamic Programming
The worst case time complexity of recursive solution is O(2n ). The above recursive solution
certainly has many overlapping subproblems. For example, if wee consider A = “XXX”, B
= “XXX” and C = “XXXXXX” and draw recursion tree, there will be many overlapping
subproblems.
Therefore, like other typical Dynamic Programming problems, we can solve it by creating a
table and store results of subproblems in bottom up manner. Thanks to Abhinav Ramana
for suggesting this method and implementation.
334
Chapter 33. DP-33 | Find if a string is interleaved of two other strings
// A is empty
else if (i==0 && B[j-1]==C[j-1])
IL[i][j] = IL[i][j-1];
// B is empty
else if (j==0 && A[i-1]==C[i-1])
IL[i][j] = IL[i-1][j];
// Current character of C matches with current character of A,
// but doesn't match with current character of B
else if(A[i-1]==C[i+j-1] && B[j-1]!=C[i+j-1])
IL[i][j] = IL[i-1][j];
// Current character of C matches with current character of B,
// but doesn't match with current character of A
else if (A[i-1]!=C[i+j-1] && B[j-1]==C[i+j-1])
IL[i][j] = IL[i][j-1];
// Current character of C matches with that of both A and B
else if (A[i-1]==C[i+j-1] && B[j-1]==C[i+j-1])
IL[i][j]=(IL[i-1][j] || IL[i][j-1]) ;
}
}
return IL[M][N];
}
// A function to run test cases
void test(char *A, char *B, char *C)
{
if (isInterleaved(A, B, C))
cout << C <<" is interleaved of " << A <<" and " << B << endl;
else
cout << C <<" is not interleaved of " << A <<" and " << B << endl;
}
// Driver program to test above functions
int main()
{
test("XXY", "XXZ", "XXZXXXY");
test("XY" ,"WZ" ,"WZXY");
test ("XY", "X", "XXY");
test ("YX", "X", "XXY");
test ("XXY", "XXZ", "XXXXZY");
return 0;
}
335
Chapter 33. DP-33 | Find if a string is interleaved of two other strings
Output:
Source
https://www.geeksforgeeks.org/find-if-a-string-is-interleaved-of-two-other-strings-dp-33/
336
Chapter 34
The following information can be extracted from the problem statement to make it simpler:
337
Chapter 34. DP-34 | Assembly Line Scheduling
338
Chapter 34. DP-34 | Assembly Line Scheduling
The total minimum time taken by the car chassis to come out of the factory is given by:
Tmin = min(Time taken to leave station Si,n + Time taken to exit the car factory)
Tmin = min(T1(n) + x1 , T2(n) + x2 )
Why dynamic programming?
The above recursion exhibits overlapping sub-problems. There are two ways to reach station
S1, j :
So, to find the minimum time to leave station S1, j the minimum time to leave the previous
two stations must be calculated(as explained in above recursion).
Similarly, there are two ways to reach station S2, j :
Please note that the minimum times to leave stations S1, j-1 and S2, j-1 have already been
calculated.
So, we need two tables to store the partial results calculated for each station in an assembly
line. The table will be filled in bottom-up fashion.
Note:
In this post, the word “leave” has been used in place of “reach” to avoid the confusion. Since
the car chassis must spend a fixed time in each station, the word leave suits better.
Implementation:
C
339
Chapter 34. DP-34 | Assembly Line Scheduling
{
T1[i] = min(T1[i-1] + a[0][i], T2[i-1] + t[1][i] + a[0][i]);
T2[i] = min(T2[i-1] + a[1][i], T1[i-1] + t[0][i] + a[1][i]);
}
// Consider exit times and retutn minimum
return min(T1[NUM_STATION-1] + x[0], T2[NUM_STATION-1] + x[1]);
}
int main()
{
int a[][NUM_STATION] = {{4, 5, 3, 2},
{2, 10, 1, 4}};
int t[][NUM_STATION] = {{0, 7, 4, 5},
{0, 9, 2, 8}};
int e[] = {10, 12}, x[] = {18, 7};
printf("%d", carAssembly(a, t, e, x));
return 0;
}
Output:
35
Java
340
Chapter 34. DP-34 | Assembly Line Scheduling
Python3
341
Chapter 34. DP-34 | Assembly Line Scheduling
C#
342
Chapter 34. DP-34 | Assembly Line Scheduling
static int carAssembly(int [,]a, int [,]t,
int []e, int []x)
{
int []T1= new int [NUM_STATION];
int []T2 =new int[NUM_STATION] ;
int i;
// time taken to leave first station
// in line 1
T1[0] = e[0] + a[0,0];
// time taken to leave first station
// in line 2
T2[0] = e[1] + a[1,0];
// Fill tables T1[] and T2[] using
// the above given recursive relations
for (i = 1; i < NUM_STATION; ++i)
{
T1[i] = min(T1[i - 1] + a[0,i],
T2[i - 1] + t[1,i] + a[0,i]);
T2[i] = min(T2[i - 1] + a[1,i],
T1[i - 1] + t[0,i] + a[1,i]);
}
// Consider exit times and retutn
// minimum
return min(T1[NUM_STATION-1] + x[0],
T2[NUM_STATION-1] + x[1]);
}
// Driver code
public static void Main ()
{
int [,]a = { {4, 5, 3, 2},
{2, 10, 1, 4} };
int [,]t = { {0, 7, 4, 5},
{0, 9, 2, 8} };
int []e = {10, 12};
int []x = {18, 7};
Console.Write(carAssembly(a, t, e, x));
}
}
343
Chapter 34. DP-34 | Assembly Line Scheduling
// This code is contributed by nitin mittal.
PHP
<?php
// A PHP program to find minimum
// possible time by the car chassis
// to complete
$NUM_LINE = 2;
$NUM_STATION = 4;
// Utility function to find
// minimum of two numbers
function carAssembly($a, $t,
$e, $x)
{
global $NUM_LINE,
$NUM_STATION;
$T1 = array();
$T2 = array();
$i;
$T1[0] = $e[0] + $a[0][0]; // time taken to leave
// first station in line 1
$T2[0] = $e[1] + $a[1][0]; // time taken to leave
// first station in line 2
// Fill tables T1[] and T2[]
// using the above given
// recursive relations
for ($i = 1;
$i < $NUM_STATION; ++$i)
{
$T1[$i] = min($T1[$i - 1] + $a[0][$i],
$T2[$i - 1] + $t[1][$i] +
$a[0][$i]);
$T2[$i] = min($T2[$i - 1] + $a[1][$i],
$T1[$i - 1] + $t[0][$i] +
$a[1][$i]);
}
// Consider exit times
// and return minimum
return min($T1[$NUM_STATION - 1] + $x[0],
$T2[$NUM_STATION - 1] + $x[1]);
}
344
Chapter 34. DP-34 | Assembly Line Scheduling
// Driver Code
$a = array(array(4, 5, 3, 2),
array(2, 10, 1, 4));
$t = array(array(0, 7, 4, 5),
array(0, 9, 2, 8));
$e = array(10, 12);
$x = array(18, 7);
echo carAssembly($a, $t, $e, $x);
// This code is contributed
// by anuj_67.
?>
Output:
35
The bold line shows the path covered by the car chassis for given input values.
Exercise:
Extend the above algorithm to print the path covered by the car chassis in the factory.
References:
Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E.
Leiserson, Ronald L. Rivest
This article is compiled by Aashish Barnwal. 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
Source
https://www.geeksforgeeks.org/assembly-line-scheduling-dp-34/
345
Chapter 35
For simplicity, we have assumed that the given set is sorted. We can always add a pre-
processing step to first sort the set and then apply the below algorithms.
A simple solution is to one by one consider every pair as first two elements of AP and
check for the remaining elements in sorted set. To consider all pairs as first two elements,
we need to run a O(n^2) nested loop. Inside the nested loops, we need a third loop which
linearly looks for the more elements in Arithmetic Progression (AP). This process takes
O(n3 ) time.
We can solve this problem in O(n2 ) time using Dynamic Programming. To get idea of
the DP solution, let us first discuss solution of following simpler problem.
Given a sorted set, find if there exist three elements in Arithmetic Progression
or not
Please note that, the answer is true if there are 3 or more elements in AP, otherwise false.
346
Chapter 35. DP-35 | Longest Arithmetic Progression
To find the three elements, we first fix an element as middle element and search for other
two (one smaller and one greater). We start from the second element and fix every element
as middle element. For an element set[j] to be middle of AP, there must exist elements ‘set[i]’
and ‘set[k]’ such that set[i] + set[k] = 2*set[j] where 0 <= i < j and j < k <=n-1. How
to efficiently find i and k for a given j? We can find i and k in linear time using following
simple algorithm.
Following is C++ implementation of the above algorithm for the simpler problem.
347
Chapter 35. DP-35 | Longest Arithmetic Progression
To fill rest of the table, j (second element in AP) is first fixed. i and k are searched for a
fixed j. If i and k are found such that i, j, k form an AP, then the value of L[i][j] is set as
L[j][k] + 1. Note that the value of L[j][k] must have been filled before as the loop traverses
from right to left columns.
Following is the implementation of the Dynamic Programming algorithm.
C++
// C++ program to find Length of the Longest AP (llap) in a given sorted set.
// The code strictly implements the algorithm provided in the reference.
#include <iostream>
using namespace std;
// Returns length of the longest AP subset in a given set
int lenghtOfLongestAP(int set[], int n)
{
if (n <= 2) return n;
// Create a table and initialize all values as 2. The value of
// L[i][j] stores LLAP with set[i] and set[j] as first two
// elements of AP. Only valid entries are the entries where j>i
int L[n][n];
int llap = 2; // Initialize the result
// Fill entries in last column as 2. There will always be
// two elements in AP with last number of set as second
// element in AP
for (int i = 0; i < n; i++)
L[i][n-1] = 2;
// Consider every element as second element of AP
for (int j=n-2; j>=1; j--)
{
// Search for i and k for j
int i = j-1, k = j+1;
while (i >= 0 && k <= n-1)
{
if (set[i] + set[k] < 2*set[j])
k++;
// Before changing i, set L[i][j] as 2
else if (set[i] + set[k] > 2*set[j])
{ L[i][j] = 2, i--; }
else
{
// Found i and k for j, LLAP with i and j as first two
348
Chapter 35. DP-35 | Longest Arithmetic Progression
Java
349
Chapter 35. DP-35 | Longest Arithmetic Progression
350
Chapter 35. DP-35 | Longest Arithmetic Progression
351
Chapter 35. DP-35 | Longest Arithmetic Progression
Output:
4
3
5
Source
https://www.geeksforgeeks.org/longest-arithmetic-progression-dp-35/
352
Chapter 36
Input: n = 2
Output: 1 (Maximum obtainable product is 1*1)
Input: n = 3
Output: 2 (Maximum obtainable product is 1*2)
Input: n = 4
Output: 4 (Maximum obtainable product is 2*2)
Input: n = 5
Output: 6 (Maximum obtainable product is 2*3)
Input: n = 10
Output: 36 (Maximum obtainable product is 3*3*4)
1) Optimal Substructure:
This problem is similar to Rod Cutting Problem. We can get the maximum product by
making a cut at different positions and comparing the values obtained after a cut. We can
recursively call the same function for a piece obtained after a cut.
Let maxProd(n) be the maximum product for a rope of length n. maxProd(n) can be
written as following.
353
Chapter 36. DP-36 | Maximum Product Cutting
C++
Java
354
Chapter 36. DP-36 | Maximum Product Cutting
Python3
355
Chapter 36. DP-36 | Maximum Product Cutting
# Driver program to test above functions
print("Maximum Product is ", maxProd(10));
# This cide is contributed
# by Sumit Sudhakar
C#
356
Chapter 36. DP-36 | Maximum Product Cutting
Output:
Maximum Product is 36
Considering the above implementation, following is recursion tree for a Rope of length 5.
In the above partial recursion tree, mP(3) is being solved twice. We can see that there
are many subproblems which are solved again and again. Since same suproblems are called
again, this problem has Overlapping Subprolems property. So the problem has both prop-
erties (see thisand this) of a dynamic programming problem. Like other typical Dynamic
Programming(DP) problems, recomputations of same subproblems can be avoided by con-
structing a temporary array val[] in bottom up manner.
357
Chapter 36. DP-36 | Maximum Product Cutting
val[i] = max_val;
}
return val[n];
}
Time Complexity of the Dynamic Programming solution is O(n^2) and it requires O(n)
extra space.
A Tricky Solution:
If we see some examples of this problems, we can easily observe following pattern.
The maximum product can be obtained be repeatedly cutting parts of size 3 while size
is greater than 4, keeping the last part as size of 2 or 3 or 4. For example, n = 10, the
maximum product is obtained by 3, 3, 4. For n = 11, the maximum product is obtained
by 3, 3, 3, 2. Following is the implementation of this approach.
C++
#include <iostream>
using namespace std;
/* The main function that teturns the max possible product */
int maxProd(int n)
{
// n equals to 2 or 3 must be handled explicitly
if (n == 2 || n == 3) return (n-1);
// Keep removing parts of size 3 while n is greater than 4
int res = 1;
while (n > 4)
{
n -= 3;
res *= 3; // Keep multiplying 3 to res
}
return (n * res); // The last part multiplied by previous parts
}
/* Driver program to test above functions */
int main()
{
cout << "Maximum Product is " << maxProd(10);
return 0;
}
Java
358
Chapter 36. DP-36 | Maximum Product Cutting
class GFG {
/* The main function that returns the
max possible product */
static int maxProd(int n)
{
// n equals to 2 or 3 must be handled
// explicitly
if (n == 2 || n == 3) return (n-1);
// Keep removing parts of size 3
// while n is greater than 4
int res = 1;
while (n > 4)
{
n -= 3;
// Keep multiplying 3 to res
res *= 3;
}
// The last part multiplied by
// previous parts
return (n * res);
}
/* Driver program to test above functions */
public static void main(String[] args)
{
System.out.println("Maximum Product is "
+ maxProd(10));
}
}
// This code is contributed by Prerna Saini
Python3
359
Chapter 36. DP-36 | Maximum Product Cutting
# Keep removing parts of size 3
# while n is greater than 4
res = 1
while (n > 4):
n -= 3;
# Keep multiplying 3 to res
res *= 3;
# The last part multiplied
# by previous parts
return (n * res)
# Driver program to test above functions
print("Maximum Product is ", maxProd(10));
# This code is contributed
# by Sumit Sudhakar
C#
360
Chapter 36. DP-36 | Maximum Product Cutting
PHP
<?php
/* The main function that returns
the max possible product */
function maxProd($n)
{
// n equals to 2 or 3 must
// be handled explicitly
if ($n == 2 || $n == 3)
return ($n - 1);
// Keep removing parts of size
// 3 while n is greater than 4
$res = 1;
while ($n > 4)
{
$n = $n - 3;
// Keep multiplying 3 to res
$res = $res * 3;
}
// The last part multiplied
// by previous parts
return ($n * $res);
}
// Driver code
echo ("Maximum Product is ");
echo(maxProd(10));
// This code is contributed
// by Shivi_Aggarwal
?>
361
Chapter 36. DP-36 | Maximum Product Cutting
Output:
Maximum Product is 36
Improved By : Shivi_Aggarwal
Source
https://www.geeksforgeeks.org/maximum-product-cutting-dp-36/
362
Chapter 37
DP-37 | Boolean
Parenthesization Problem
Symbols
'T' ---> true
'F' ---> false
Operators
& ---> boolean AND
| ---> boolean OR
^ ---> boolean XOR
Count the number of ways we can parenthesize the expression so that the value of expression
evaluates to true.
Let the input be in form of two arrays one contains the symbols (T and F) in order and
other contains operators (&, | and ^}
Examples:
363
Chapter 37. DP-37 | Boolean Parenthesization Problem
Solution:
Let T(i, j) represents the number of ways to parenthesize the symbols between i and j
(both inclusive) such that the subexpression between i and j evaluates to true.
Let F(i, j) represents the number of ways to parenthesize the symbols between i and j (both
inclusive) such that the subexpression between i and j evaluates to false.
Base Cases:
364
Chapter 37. DP-37 | Boolean Parenthesization Problem
If we draw recursion tree of above recursive solution, we can observe that it many overlapping
subproblems. Like other dynamic programming problems, it can be solved by filling a table
in bottom up manner. Following is C++ implementation of dynamic programming solution.
#include<iostream>
#include<cstring>
using namespace std;
// Returns count of all possible parenthesizations that lead to
// result true for a boolean expression with symbols like true
// and false and operators like &, | and ^ filled between symbols
int countParenth(char symb[], char oper[], int n)
{
int F[n][n], T[n][n];
// Fill diaginal entries first
// All diagonal entries in T[i][i] are 1 if symbol[i]
// is T (true). Similarly, all F[i][i] entries are 1 if
// symbol[i] is F (False)
for (int i = 0; i < n; i++)
{
F[i][i] = (symb[i] == 'F')? 1: 0;
T[i][i] = (symb[i] == 'T')? 1: 0;
}
// Now fill T[i][i+1], T[i][i+2], T[i][i+3]... in order
// And F[i][i+1], F[i][i+2], F[i][i+3]... in order
for (int gap=1; gap<n; ++gap)
{
for (int i=0, j=gap; j<n; ++i, ++j)
{
T[i][j] = F[i][j] = 0;
for (int g=0; g<gap; g++)
{
// Find place of parenthesization using current value
// of gap
int k = i + g;
// Store Total[i][k] and Total[k+1][j]
int tik = T[i][k] + F[i][k];
int tkj = T[k+1][j] + F[k+1][j];
// Follow the recursive formulas according to the current
// operator
if (oper[k] == '&')
{
T[i][j] += T[i][k]*T[k+1][j];
F[i][j] += (tik*tkj - T[i][k]*T[k+1][j]);
365
Chapter 37. DP-37 | Boolean Parenthesization Problem
}
if (oper[k] == '|')
{
F[i][j] += F[i][k]*F[k+1][j];
T[i][j] += (tik*tkj - F[i][k]*F[k+1][j]);
}
if (oper[k] == '^')
{
T[i][j] += F[i][k]*T[k+1][j] + T[i][k]*F[k+1][j];
F[i][j] += T[i][k]*T[k+1][j] + F[i][k]*F[k+1][j];
}
}
}
}
return T[0][n-1];
}
// Driver program to test above function
int main()
{
char symbols[] = "TTFT";
char operators[] = "|&^";
int n = strlen(symbols);
// There are 4 ways
// ((T|T)&(F^T)), (T|(T&(F^T))), (((T|T)&F)^T) and (T|((T&F)^T))
cout << countParenth(symbols, operators, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/boolean-parenthesization-problem-dp-37/
366
Chapter 38
Input : W = 10, n = 3
val[] = {7, 8, 4}
wt[] = {3, 8, 6}
Output: 11
We get maximum value by picking items of 3 KG and 6 KG.
We have discussed a Dynamic Programming based solution here. In the previous solution, we
used a n * W matrix. We can reduce the used extra space. The idea behind the optimization
is, to compute mat[i][j], we only need solution of previous row. In 0-1 Knapsack Problem if
we are currently on mat[i][j] and we include ith element then we move j-wt[i] steps back in
previous row and if we exclude the current element we move on jth column in previous row.
So here we can observe that at a time we are working only with 2 consecutive rows.
In below solution, we create a matrix of size 2*W. If n is odd, then final answer will be at
mat[0][W] and if n is even then final answer will be at mat[1][W] because index starts from
0.
367
Chapter 38. A Space Optimized DP solution for 0-1 Knapsack Problem
368
Chapter 38. A Space Optimized DP solution for 0-1 Knapsack Problem
mat[0][j] = mat[1][j];
}
}
i++;
}
// Return mat[0][W] if n is odd, else mat[1][W]
return (n%2 != 0)? mat[0][W] : mat[1][W];
}
// Driver program to test the cases
int main()
{
int val[] = {7, 8, 4}, wt[] = {3, 8, 6}, W = 10, n = 3;
cout << KnapSack(val, wt, n, W) << endl;
return 0;
}
Output:
11
369
Chapter 38. A Space Optimized DP solution for 0-1 Knapsack Problem
Output:
11
Source
https://www.geeksforgeeks.org/space-optimized-dp-solution-0-1-knapsack-problem/
370
Chapter 39
371
Chapter 39. A Space Optimized Solution of LCS
We strongly recommend that you click here and practice it, before moving on
to the solution.
One important observation in above simple implementation is, in each iteration of outer
loop we only, need values from all columns of previous row. So there is no need of
storing all rows in our DP matrix, we can just store two rows at a time and use them, in that
way used space will reduce from L[m+1][n+1] to L[2][n+1]. Below is the implementation
of above idea.
C++
372
Chapter 39. A Space Optimized Solution of LCS
bi = i & 1;
for (int j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[bi][j] = 0;
else if (X[i-1] == Y[j-1])
L[bi][j] = L[1 - bi][j - 1] + 1;
else
L[bi][j] = max(L[1 - bi][j],
L[bi][j - 1]);
}
}
// Last filled entry contains
// length of LCS
// for X[0..n-1] and Y[0..m-1]
return L[bi][n];
}
// Driver code
int main()
{
string X = "AGGTAB";
string Y = "GXTXAYB";
printf("Length of LCS is %d\n", lcs(X, Y));
return 0;
}
Java
373
Chapter 39. A Space Optimized Solution of LCS
374
Chapter 39. A Space Optimized Solution of LCS
Python3
C#
375
Chapter 39. A Space Optimized Solution of LCS
376
Chapter 39. A Space Optimized Solution of LCS
Output:
Length of LCS is 4
Source
https://www.geeksforgeeks.org/space-optimized-solution-lcs/
377
Chapter 40
We can solve this problem by parenthesizing all possible valid substring of the expression
and then evaluating them, but as we can see that it will involve solving lots of repeating
subproblem, to save ourselves we can follow a dynamic programming approach.
We store the result for each substring in a map and if string in recursion is already solved,
we return result from map instead of solving that again.
Below code runs a loop in the string and if at any instant, character is operator then we
divide the input from there, recursively solve each part and then combine the result in all
possible ways.
See the use of c_str() function, this function converts the C++ string into C char array,
378
Chapter 40. All ways to add parenthesis for evaluation
this function is used in below code because atoi() function expects a character array as an
argument not the string. It converts character array to number.
379
Chapter 40. All ways to add parenthesis for evaluation
}
}
// if input contains only number then save that
// into res vector
if (res.size() == 0)
res.push_back(atoi(input.c_str()));
// Store in memo so that input string is not
// processed repeatedly
memo[input] = res;
return res;
}
// method to return all possible output
// from input expression
vector<int> possibleResult(string input)
{
map< string, vector<int> > memo;
return possibleResultUtil(input, memo);
}
// Driver code to test above methods
int main()
{
string input = "5*4-3*2";
vector<int> res = possibleResult(input);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Output:
-10 10 14 10 34
Source
https://www.geeksforgeeks.org/all-ways-to-add-parenthesis-for-evaluation/
380
Chapter 41
Input : N = 7
Output : 0 1 3 8
Input : N = 15
Output : 0 1 3 8 21 55 144 377
Source
https://www.geeksforgeeks.org/alternate-fibonacci-numbers/
C++
381
Chapter 41. Alternate Fibonacci Numbers
/* 0th and 1st number of the series are 0 and 1*/
int f1 = 0;
int f2 = 1;
cout << f1 << " ";
for (int i = 2; i <= n; i++) {
int f3 = f2 + f1;
if (i % 2 == 0)
cout << f3 << " ";
f1 = f2;
f2 = f3;
}
}
int main()
{
int N = 15;
alternateFib(N);
return 0;
}
Java
382
Chapter 41. Alternate Fibonacci Numbers
C#
// Alternate Fibonacci Series
// using Dynamic Programming
using System;
class GFG
{
static void alternateFib(int n)
{
if (n < 0) return; /* 0th and 1st number of the series are 0 and 1*/ int f1 = 0; int f2 = 1;
Console.Write(f1 + ” ”); for (int i = 2; i <= n; i++) { int f3 = f2 + f1; if (i % 2 == 0)
Console.Write(f3 + ” ”); f1 = f2; f2 = f3; } } // Driver Code public static void Main () { int
N = 15; alternateFib(N); } } // This code is contributed // by chandan_jnu. [tabbyending]
Output:
0 1 3 8 21 55 144 377
383
Chapter 42
Balanced expressions such that given positions have opening brackets - GeeksforGeeks
Given an integer n and an array of positions ‘position[]’ (1 <= position[i] <= 2n), find the
number of ways of proper bracket expressions that can be formed of length 2n such that
given positions have opening bracket. Examples :
384
Chapter 42. Balanced expressions such that given positions have opening brackets
The base case of the DP is, DP0, 0 =1. We need to fill the first position with a ‘[‘ bracket,
and there is only way to do this.
If the position has a opening bracket sequence which can be marked by a hash array,
then the recurrence occurs as :
385
Chapter 42. Balanced expressions such that given positions have opening brackets
// iterate and formulate the recurrences
for (int i = 1; i <= 2 * n; i++) {
for (int j = 0; j <= 2 * n; j++) {
// if position has a opening bracket
if (h[i]) {
if (j != 0)
dp[i][j] = dp[i - 1][j - 1];
else
dp[i][j] = 0;
}
else {
if (j != 0)
dp[i][j] = dp[i - 1][j - 1] +
dp[i - 1][j + 1];
else
dp[i][j] = dp[i - 1][j + 1];
}
}
}
// return answer
return dp[2 * n][0];
}
// driver code
int main()
{
int n = 3;
// positions where opening braces
// will be placed
int pos[] = { 2 };
int k = sizeof(pos)/sizeof(pos[0]);
cout << arrangeBraces(n, pos, k);
return 0;
}
Output :
386
Chapter 42. Balanced expressions such that given positions have opening brackets
Source
https://www.geeksforgeeks.org/balanced-expressions-such-that-given-positions-have-opening-brackets/
387
Chapter 43
Balanced expressions such that given positions have opening brackets | Set 2 - GeeksforGeeks
Given an integer n and an array of positions ‘position[]’ (1 <= length(position[]) <= 2n),
find the number of ways of proper bracket expressions that can be formed of length 2n such
that given positions have the opening bracket.
Note: position[] array is given in the form of (1-based indexing) [0, 1, 1, 0]. Here 1
denotes the positions at which open bracket should be placed. At positions with value 0,
either of opening and closing bracket can be placed.
Examples:
Dynamic Programming approach of this problem has been already discussed here. In this
post, recursive and recursion using memoization approach will be discussed.
Algorithm–
388
Chapter 43. Balanced expressions such that given positions have opening brackets | Set 2
1. Mark all the positions with open brackets in the given array adj as 1.
2. Run a recursive loop, such that –
• If count of total brackets(opening brackets subracted from closing brackets is less
than zero), return 0.
• If the index reaches till n and if the total brackets=0, then a solution is obtained
and return 1, otherwise return 0.
• If the index has 1 pre-assigned to it, return the function recursively with index+1
and increment the total brackets.
• Otherwise Return the function recursively by inserting open brackets at that
index and incrementing total brackets by 1 + inserting closed brackets at that
index and decrementing total brackets by 1 and move on to the next index till n.
389
Chapter 43. Balanced expressions such that given positions have opening brackets | Set 2
Output:
Memoized Approach: Time complexity of the above algorithm can be optimized by using
Memorization. The only thing to be done is to use an array to store the results of previous
iterations so that there is no need to recursively call the same function more than once, if
the value is already calculated.
Below is the required implementation:
390
Chapter 43. Balanced expressions such that given positions have opening brackets | Set 2
// If index reaches the end of expression
if (index == n) {
// If brackets are balanced
if (openbrk == 0)
return 1;
else
return 0;
}
// If already stored in dp
if (dp[index][openbrk] != -1)
return dp[index][openbrk];
// If the current index has assigned open bracket
if (adj[index] == 1) {
// Move forward increasing the
// length of open brackets
dp[index][openbrk] = find(index + 1,
openbrk + 1, n, dp, adj);
}
else {
// Move forward by inserting open as
// well as closed brackets on that index
dp[index][openbrk] = find(index + 1, openbrk + 1, n, dp, adj)
+ find(index + 1, openbrk - 1, n, dp, adj);
}
// return the answer
return dp[index][openbrk];
}
// Driver Code
int main()
{
// DP array to precompute the answer
int dp[N][N];
int n = 2;
memset(dp, -1, sizeof(dp));
// Open brackets at postion 1
int adj[4] = { 1, 0, 0, 0 };
// Calling the find function to calculate the answer
cout << find(0, 0, 2 * n, dp, adj) << endl;
391
Chapter 43. Balanced expressions such that given positions have opening brackets | Set 2
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/balanced-expressions-such-that-given-positions-have-opening-brackets-set-2/
392
Chapter 44
Input: n = 2
Output: Number of ways = 2
Explanation: Let the set be {1, 2}
{ {1}, {2} }
{ {1, 2} }
Input: n = 3
Output: Number of ways = 5
Explanation: Let the set be {1, 2, 3}
{ {1}, {2}, {3} }
{ {1}, {2, 3} }
{ {2}, {1, 3} }
{ {3}, {1, 2} }
{ {1, 2, 3} }.
Value of S(n, k) can be defined recursively as, S(n+1, k) = k*S(n, k) + S(n, k-1)
393
Chapter 44. Bell Numbers (Number of ways to Partition a Set)
1
1 2
2 3 5
5 7 10 15
15 20 27 37 52
Interpretation
Then Bell(n, k) counts the number of partitions of the set {1, 2, …, n + 1} in which the
element k + 1 is the largest element that can be alone in its set.
For example, Bell(3, 2) is 3, it is count of number of partitions of {1, 2, 3, 4} in which 3 is
the largest singleton element. There are three such partitions:
394
Chapter 44. Bell Numbers (Number of ways to Partition a Set)
C++
Java
395
Chapter 44. Bell Numbers (Number of ways to Partition a Set)
{
// Explicitly fill for j = 0
bell[i][0] = bell[i-1][i-1];
// Fill for remaining values of j
for (int j=1; j<=i; j++)
bell[i][j] = bell[i-1][j-1] + bell[i][j-1];
}
return bell[n][0];
}
// Driver program
public static void main (String[] args)
{
for (int n=0; n<=5; n++)
System.out.println("Bell Number "+ n +
" is "+bellNumber(n));
}
}
// This code is contributed by Pramod Kumar
Python3
396
Chapter 44. Bell Numbers (Number of ways to Partition a Set)
C#
PHP
<?php
// A PHP program to find
// n'th Bell number
397
Chapter 44. Bell Numbers (Number of ways to Partition a Set)
Output:
Bell Number 0 is 1
Bell Number 1 is 1
Bell Number 2 is 2
Bell Number 3 is 5
Bell Number 4 is 15
Bell Number 5 is 52
Time Complexity of above solution is O(n2 ). We will soon be discussing other more efficient
methods of computing Bell Numbers.
Another problem that can be solved by Bell Numbers.
A number is squarefree if it is not divisible by a perfect square other than 1. For example,
6 is a square free number but 12 is not as it is divisible by 4.
Given a squarefree number x, find the number of different multiplicative partitions of x. The
number of multiplicative partitions is Bell(n) where n is number of prime factors of x. For
398
Chapter 44. Bell Numbers (Number of ways to Partition a Set)
example x = 30, there are 3 prime factors of 2, 3 and 5. So the answer is Bell(3) which is 5.
The 5 partitions are 1 x 30, 2 x15, 3 x 10, 5 x 6 and 2 x 3 x 5.
Exercise:
The above implementation causes arithmetic overflow for slightly larger values of n. Ex-
tend the above program so that results are computed under modulo 1000000007 to avoid
overflows.
Reference:
https://en.wikipedia.org/wiki/Bell_number
https://en.wikipedia.org/wiki/Bell_triangle
This article is contributed by Rajeev Agrawal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : nitin mittal, jit_t
Source
https://www.geeksforgeeks.org/bell-numbers-number-of-ways-to-partition-a-set/
399
Chapter 45
Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique cap to every
person) - GeeksforGeeks
Consider the below problems statement.
There are 100 different types of caps each having a unique id from 1 to 100. Also, there
are ‘n’ persons each having a collection of a variable number of caps. One day all of these
persons decide to go in a party wearing a cap but to look unique they decided that none of
them will wear the same type of cap. So, count the total number of arrangements or ways
such that none of them is wearing the same type of cap.
Constraints: 1 <= n <= 10 Example:
The first line contains the value of n, next n lines contain collections
of all the n persons.
Input:
3
5 100 1 // Collection of the first person.
2 // Collection of the second person.
5 100 // Collection of the third person.
Output:
4
Explanation: All valid possible ways are (5, 2, 100), (100, 2, 5),
(1, 2, 5) and (1, 2, 100)
400
Chapter 45. Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique
cap to every person)
Let i be the current cap number (caps from 1 to i-1 are already
processed). Let integer variable mask indicates that the persons w
earing and not wearing caps. If i'th bit is set in mask, then
i'th person is wearing a cap, else not.
401
Chapter 45. Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique
cap to every person)
Note that the expression "mask | (1 << j)" sets j'th bit in mask.
And a person can wear cap i if it is there in the person's cap list
provided as input.
If we draw the complete recursion tree, we can observe that many subproblems are solved
again and again. So we use Dynamic Programming. A table dp[][] is used such that in every
entry dp[i][j], i is mask and j is cap number.
Since we want to access all persons that can wear a given cap, we use an array of vectors,
capList[101]. A value capList[i] indicates the list of persons that can wear cap i.
Below is the implementation of above idea.
C/C++
402
Chapter 45. Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique
cap to every person)
// If not everyone is wearing a cap and also there are no more
// caps left to process, so there is no way, thus return 0;
if (i > 100) return 0;
// If we already have solved this subproblem, return the answer.
if (dp[mask][i] != -1) return dp[mask][i];
// Ways, when we don't include this cap in our arrangement
// or solution set.
long long int ways = countWaysUtil(mask, i+1);
// size is the total number of persons having cap with id i.
int size = capList[i].size();
// So, assign one by one ith cap to all the possible persons
// and recur for remaining caps.
for (int j = 0; j < size; j++)
{
// if person capList[i][j] is already wearing a cap so continue as
// we cannot assign him this cap
if (mask & (1 << capList[i][j])) continue;
// Else assign him this cap and recur for remaining caps with
// new updated mask vector
else ways += countWaysUtil(mask | (1 << capList[i][j]), i+1);
ways %= MOD;
}
// Save the result and return it.
return dp[mask][i] = ways;
}
// Reads n lines from standard input for current test case
void countWays(int n)
{
//----------- READ INPUT --------------------------
string temp, str;
int x;
getline(cin, str); // to get rid of newline character
for (int i=0; i<n; i++)
{
getline(cin, str);
stringstream ss(str);
// while there are words in the streamobject ss
while (ss >> temp)
{
403
Chapter 45. Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique
cap to every person)
stringstream s;
s << temp;
s >> x;
// add the ith person in the list of cap if with id x
capList[x].push_back(i);
}
}
//----------------------------------------------------
// All mask is used to check whether all persons
// are included or not, set all n bits as 1
allmask = (1 << n) - 1;
// Initialize all entries in dp as -1
memset(dp, -1, sizeof dp);
// Call recursive function count ways
cout << countWaysUtil(0, 1) << endl;
}
// Driver Program
int main()
{
int n; // number of persons in every test case
cin >> n;
countWays(n);
return 0;
}
Java
404
Chapter 45. Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique
cap to every person)
405
Chapter 45. Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique
cap to every person)
// Save the result and return it.
return dp[mask][i] = (int) ways;
}
// Reads n lines from standard input for current test case
static void countWays(int n) throws Exception
{
//----------- READ INPUT --------------------------
String str;
String split[];
int x;
for (int i=0; i<n; i++)
{
str = br.readLine();
split = str.split(" ");
// while there are words in the split[]
for (int j = 0; j < split.length; j++) {
// add the ith person in the list of cap if with id x
x = Integer.parseInt(split[j]);
capList[x].add(i);
}
}
//----------------------------------------------------
// All mask is used to check of all persons
// are included or not, set all n bits as 1
allmask = (1 << n) - 1;
// Initialize all entries in dp as -1
for (int[] is : dp) {
for (int i = 0; i < is.length; i++) {
is[i] = -1;
}
}
// Call recursive function count ways
System.out.println(countWaysUtil(0, 1));
}
// Driver method
public static void main(String args[]) throws Exception
{
int n; // number of persons in every test case
406
Chapter 45. Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique
cap to every person)
Python
407
Chapter 45. Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique
cap to every person)
# assign ith cap one by one to all the possible persons
# and recur for remaining caps.
if cap_no in self.caps:
for ppl in self.caps[cap_no]:
# if person 'ppl' is already wearing a cap then continue
if mask & (1 << ppl) : continue
# Else assign him this cap and recur for remaining caps with
# new updated mask vector
ways += self.countWaysUtil(dp, mask | (1 << ppl), cap_no + 1)
ways = ways % (10**9 + 7)
# Save the result and return it
dp[mask][cap_no] = ways
return dp[mask][cap_no]
def countWays(self,N):
# Reads n lines from standard input for current test case
# create dictionary for cap. cap[i] = list of person having
# cap no i
for ppl in range(N):
cap_possessed_by_person = map(int, raw_input().strip().split())
for i in cap_possessed_by_person:
self.caps[i].append(ppl)
# allmask is used to check if all persons
# are included or not, set all n bits as 1
self.allmask = (1 << N) -1
# Initialize all entries in dp as -1
dp = [[-1 for j in range(self.total_caps + 1)] for i in range(2 ** N)]
# Call recursive function countWaysUtil
# result will be in dp[0][1]
print self.countWaysUtil(dp, 0, 1,)
#Driver Program
408
Chapter 45. Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique
cap to every person)
def main():
No_of_people = input() # number of persons in every test case
AssignCap().countWays(No_of_people)
if __name__ == '__main__':
main()
# This code is contributed by Neelam Yadav
Input:
3
5 100 1
2
5 100
Output:
This article is contributed by Gaurav Ahirwar. 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/bitmasking-and-dynamic-programming-set-1-count-ways-to-assign-unique-cap-to-ev
409
Chapter 46
Problem Description:
410
Chapter 46. Bitmasking and Dynamic Programming | Set-2 (TSP)
The first part is to calculate the minimum distance between the two cells. We can do it by
simply using a BFS as all the distances are unit distance. To optimize our solution we will
be pre-calculating the distances taking the initial location and the location of the houses as
the source point for our BFS.
Each BFS traversal takes O(size of grid) time. Therefore, it is O(X * size_of_grid) for
overall pre-calculation, where X = number of houses + 1 (initial position)
Now lets’s think of a DP state
So we will be needing to track the visited houses and the last visited house to uniquely
identify a state in this problem.
Therefore, we will be taking dp[index][mask] as our DP state.
Here,
index : tells us the location of current house
mask : tells us the houses that are visited ( if ith bit is set in mask then this means that
the ith dirty tile is cleaned)
Whereas dp[index][mask] will tell us the minimum distance to visit X(number of set bits in
mask) houses corresponding to their order of their occurrence in the mask where the last
visited house is house at location index.
State transition relation
So our initial state will be dp[0][0] this tells that we are currently at initial tile that is our
initial location and mask is 0 that states that no house is visited till now.
And our final destination state will be dp[any index][LIMIT_MASK], here
LIMIT_MASK = (1<<N) – 1
and N = number of houses.
Therefore our DP state transition can be stated as
dp(curr_idx)(curr_mask) = min{
for idx : off_bits_in_curr_mask
dp(idx)(cur_mask.set_bit(idx)) + dist[curr_idx][idx]
}
The above relation can be visualized as the minimum distance to visit all the houses by
standing at curr_idx house and by already visiting cur_mask houses is equal to min of
distance between the curr_idx house and idx house + minimum distance to visit all the
houses by standing at idx house and by already
visiting ( cur_mask | (1 <<idx) ) houses.
So, here we iterate over all possible idx values such that cur_mask has ith bit as 0 that tells
us that ith house is not visited.
Whenever we have our mask = LIMIT_MASK, this means that we have visited all the
houses in the town. So, we will add the distance from the last visited town (i.e the town at
cur_idx positon) to the initial position (0, 0).
The C++ program for the above implementation is given below:
411
Chapter 46. Bitmasking and Dynamic Programming | Set-2 (TSP)
#include <bits/stdc++.h>
using namespace std;
#define INF 99999999
#define MAXR 12
#define MAXC 12
#define MAXMASK 2048
#define MAXHOUSE 12
// stores distance taking souce
// as every dirty tile
int dist[MAXR][MAXC][MAXHOUSE];
// memoization for dp states
int dp[MAXHOUSE][MAXMASK];
// stores coordinates for
// dirty tiles
vector < pair < int, int > > dirty;
// Directions
int X[] = {-1, 0, 0, 1};
int Y[] = {0, 1, -1, 0};
char arr[21][21];
// len : number of dirty tiles + 1
// limit : 2 ^ len -1
// r, c : number of rows and columns
int len, limit, r, c;
// Returns true if current position
// is safe to visit
// else returns false
// Time Complexity : O(1)
bool safe(int x, int y)
{
if (x >= r or y>= c or x<0 or y<0)
return false;
if (arr[x][y] == '#')
return false;
return true;
}
// runs BFS traversal at tile idx
// calulates distance to every cell
412
Chapter 46. Bitmasking and Dynamic Programming | Set-2 (TSP)
// in the grid
// Time Complexity : O(r*c)
void getDist(int idx){
// visited array to track visited cells
bool vis[21][21];
memset(vis, false, sizeof(vis));
// getting current positon
int cx = dirty[idx].first;
int cy = dirty[idx].second;
// initializing queue for bfs
queue < pair < int, int > > pq;
pq.push({cx, cy});
// initializing the dist to max
// because some cells cannot be visited
// by taking source cell as idx
for (int i = 0;i<= r;i++)
for (int j = 0;j<= c;j++)
dist[i][j][idx] = INF;
// base conditions
vis[cx][cy] = true;
dist[cx][cy][idx] = 0;
while (! pq.empty())
{
auto x = pq.front();
pq.pop();
for (int i = 0;i<4;i++)
{
cx = x.first + X[i];
cy = x.second + Y[i];
if (safe(cx, cy))
{
if (vis[cx][cy])
continue;
vis[cx][cy] = true;
dist[cx][cy][idx] = dist[x.first][x.second][idx] + 1;
pq.push({cx, cy});
}
}
}
}
// Dynamic Programming state transition recursion
413
Chapter 46. Bitmasking and Dynamic Programming | Set-2 (TSP)
414
Chapter 46. Bitmasking and Dynamic Programming | Set-2 (TSP)
415
Chapter 46. Bitmasking and Dynamic Programming | Set-2 (TSP)
// ...#...
// ...#.*.
// ...#...
// .*.#.*.
// ...#...
char Arr[5][7] = { {'.', '.', '.', '#', '.', '.', '.'},
{'.', '.', '.', '#', '.', '*', '.'},
{'.', '.', '.', '#', '.', '.', '.'},
{'.', '*', '.', '#', '.', '*', '.'},
{'.', '.', '.', '#', '.', '.', '.'}
};
r = 5; c = 7;
cout << "The given grid : " << endl;
for (int i = 0;i<r;i++)
{
for (int j = 0;j<c;j++)
{
cout << Arr[i][j] << " ";
arr[i][j] = Arr[i][j];
}
cout << endl;
}
// - initializitiation
// - precalculations
init();
ans = solve(0, 1);
cout << "Minimum distance for the given grid : ";
if (ans >= INF)
cout << "not possible" << endl;
else
cout << ans << endl;
return 0;
}
Output:
416
Chapter 46. Bitmasking and Dynamic Programming | Set-2 (TSP)
Note:
We have used the initial state to be dp[0][1] because we have pushed the start location at
the first position in the container of houses. Hence, our Bit Mask will be 1 as the 0th bit is
set i.e we have visited the starting location for our trip.
Time Complexity:
Consider the number of houses to be n. So, there are n * (2n ) states and at every state,
we are looping over n houses to transit over to next state and because of memoization we
are doing this looping transition only once for each state. Therefore, our Time Complexity
is O(n2 * 2n ).
Recommended:
• http://www.spoj.com/problems/CLEANRBT/
• https://www.youtube.com/watch?v=-JjA4BLQyqE
Source
https://www.geeksforgeeks.org/bitmasking-dynamic-programming-set-2-tsp/
417
Chapter 47
Approach :
A simple solution is to do BFS or DFS to find if there is a path.
A better solution is to mark all accessible nodes by changing their value to 1. First change
the value of first top left element value to 1 then in the first row get previous value and set
to current index in only first row if the value is -1 then no change then in first column do
the same.
418
Chapter 47. Check for possible path in 2D matrix
Then start from first row and first column and take previous row value and previous row
column and find max between them, and set to current index, if current index value is -1
then no change.
At the end if right bottom is 1 then return yes else return no.
C++
419
Chapter 47. Check for possible path in 2D matrix
Java
420
Chapter 47. Check for possible path in 2D matrix
}
//Driver code
public static void main(String[] args)
{
// Given array
int arr[][] = { { 0, 0, 0, -1, 0 },
{ -1, 0, 0, -1, -1 },
{ 0, 0, 0, -1, 0 },
{ -1, 0, -1, 0, -1 },
{ 0, 0, -1, 0, 0 } };
// path from arr[0][0]
// to arr[row][col]
if (isPath(arr))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed
// by prerna saini
C#
421
Chapter 47. Check for possible path in 2D matrix
PHP
<?php
// PHP program to find if
// there is path from top
// left to right bottom
$row = 5;
$col = 5;
// to find the path from
// top left to bottom right
function isPath($arr)
{
global $row, $col;
422
Chapter 47. Check for possible path in 2D matrix
$arr[0][0] = 1;
// Mark reachable (from
// top left) nodes in
// first row and first column.
for ($i = 1; $i < $row; $i++)
if ($arr[0][$i] != -1)
$arr[0][$i] = $arr[0][$i - 1];
for ($j = 1; $j < $col; $j++)
if ($arr[$j][0] != -1)
$arr[$j][0] = $arr[$j - 1][0];
// Mark reachable nodes
// in remaining matrix.
for ($i = 1; $i < $row; $i++)
for ($j = 1; $j < $col; $j++)
if ($arr[$i][$j] != -1)
$arr[$i][$j] = max($arr[$i][$j - 1],
$arr[$i - 1][$j]);
// return yes if right
// bottom index is 1
return ($arr[$row - 1][$col - 1] == 1);
}
// Driver Code
// Given array
$arr = array(array(0, 0, 0, 1, 0),
array(-1, 0, 0, -1, -1),
array(0, 0, 0, -1, 0),
array(-1, 0, -1, 0, -1),
array(0, 0, -1, 0, 0));
// path from arr[0][0]
// to arr[row][col]
if (isPath($arr))
echo "Yes";
else
echo "No";
// This code is contributed by anuj_67.
?>
Output:
423
Chapter 47. Check for possible path in 2D matrix
No
Source
https://www.geeksforgeeks.org/check-possible-path-2d-matrix/
424
Chapter 48
Input : n = 3, x = 4
a[] = {2, 4, 2}
Output : YES
There are n = 3 persons say and maximum
allowed time is x = 4 units. Let the persons
be P0, P1 and P2 and two machines be M0 and M1.
At t0 : P0 goes to M0
At t0 : P2 goes to M1
At t2 : M0 is free, p3 goes to M0
At t4 : both M0 and M1 are free and all 3 have
given their vote.
Let sum be the total time taken by all n people. If sum <=x, then answer will obviously
be YES. Otherwise, we need to check whether the given array can be split in two parts
such that sum of first part and sum of second part are both less than or equal to x. The
problem is similar to the knapsack problem. Imagine two knapsacks each with capacity x.
Now find, maximum people who can vote on any one machine i.e. find maximum subset
sum for knapsack of capacity x. Let this sum be s1. Now if (sum-s1) <= x, then answer is
YES else answer is NO.
425
Chapter 48. Check if all people can vote on two machines
Output:
426
Chapter 48. Check if all people can vote on two machines
YES
Source
https://www.geeksforgeeks.org/check-people-can-vote-two-machines/
427
Chapter 49
A simple solution is to recursively consider all possible scenarios ie either use a ;+’ or a ‘-‘
operator between the elements and maintain a variable sum which stores the result.If this
result is divisible by M then return true else return false
Recursive implementation is as follows:
428
Chapter 49. Check if any valid sequence is divisible by M
if (index == n) {
// check if sum is divisible by M
if ((sum % M) == 0)
return true;
return false;
}
// recursively call by considering '+'
// or '-' between index and index+1
// 1.Try placing '+'
bool placeAdd = isPossible(index + 1,
sum + arr[index]);
// 2. Try placing '-'
bool placeMinus = isPossible(index + 1,
sum - arr[index]);
if (placeAdd || placeMinus)
return true;
return false;
}
There are overlapping subproblems as shown in the image below (Note: the image represents
the recursion tree till index = 3)
429
Chapter 49. Check if any valid sequence is divisible by M
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1000;
bool isPossible(int n, int index, int sum,
int M, int arr[], int dp[][MAX])
{
// Base case
if (index == n) {
// check if sum is divisible by M
430
Chapter 49. Check if any valid sequence is divisible by M
if ((sum % M) == 0)
return true;
return false;
}
// check if the current state
// is already computed
if (dp[index][sum] != -1)
return dp[index][sum];
// 1.Try placing '+'
bool placeAdd = isPossible(n, index + 1,
sum + arr[index], M, arr, dp);
// 2. Try placing '-'
bool placeMinus = isPossible(n, index + 1,
sum - arr[index], M, arr, dp);
// calculate value of res for recursive case
bool res = (placeAdd || placeMinus);
// store the value for res for current
// states and return for parent call
dp[index][sum] = res;
return res;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
int M = 4;
int dp[n + 1][MAX];
memset(dp, -1, sizeof(dp));
bool res;
res = isPossible(n, 0, 0, M, arr, dp);
cout << (res ? "True" : "False") << endl;
return 0;
}
Output:
True
The Complexity of this method is O(N*sum) where sum is the maximum possible sum for
431
Chapter 49. Check if any valid sequence is divisible by M
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
int isPossible(int n, int index, int modulo,
int M, int arr[], int dp[][MAX])
{
// Calculate modulo for this call
modulo = ((modulo % M) + M) % M;
// Base case
if (index == n) {
// check if sum is divisible by M
if (modulo == 0)
return 1;
return 0;
}
// check if the current state is
// already computed
if (dp[index][modulo] != -1)
return dp[index][modulo];
// 1.Try placing '+'
int placeAdd = isPossible(n, index + 1,
modulo + arr[index], M, arr, dp);
// 2. Try placing '-'
int placeMinus = isPossible(n, index + 1,
modulo - arr[index], M, arr, dp);
// calculate value of res for recursive
// case
bool res = (placeAdd || placeMinus);
// store the value for res for current
// states and return for parent call
432
Chapter 49. Check if any valid sequence is divisible by M
dp[index][modulo] = res;
return res;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
int M = 4;
// MAX is the Maximum value M can take
int dp[n + 1][MAX];
memset(dp, -1, sizeof(dp));
bool res;
res = isPossible(n, 1, arr[0], M, arr, dp);
cout << (res ? "True" : "False") << endl;
return 0;
}
Output:
True
Source
https://www.geeksforgeeks.org/check-valid-sequence-divisible-m/
433
Chapter 50
Input : N = 3, K = 2
A[] = { 1, 1, 1 }
Output : Yes
Explanation
Replace index 0 element with -1. It will sum of array equal to k = 2.
Input : N = 4, K = 5
A[] = { 1, 2, 3, 4 }
Output : Yes
434
Chapter 50. Check if array sum can be made K by three operations on it
Also, it is possible that the intermediate sum of the array is negative, in that case do not
perform any operation and ignore it thus letting the sum be always positive because k is
always positive.
For calculating dp[i][j] we need the values of all states that can make a sum j if we apply an
operation on a[i] and add it to the sum.
Below is the C++ implementation of this approach
435
Chapter 50. Check if array sum can be made K by three operations on it
Output:
Yes
Source
https://www.geeksforgeeks.org/check-if-array-sum-can-be-made-k-by-three-operations-on-it/
436
Chapter 51
Check if it is possible to
transform one string to another
Examples:
Approach:
Let DPi, j be 1 if it is possible to convert 1st i characters of s1 to j characters of s2, else
DPi, j =0. Close observations gives us two conditions to deal with.
437
Chapter 51. Check if it is possible to transform one string to another
Initially DP0, 0 =1, if DPi, j =1 then it is possible to check for next sets using following
conditions.
1. If s1[i] in upper case is equal to s2[j] then it is possible to convert i+1 characters of s1 to
j+1 characters of s2, hence DPi+1, j+1 =1.
2. If s1[i] is in lower case, then it is possible to delete that element and hence i+1 characters
can be converted to j characters of s2. Hence DPi+1, j =1.
If DPn, m =1, then it is possible to convert s1 to s2 by following conditions.
Below is the CPP illustration of the above approach.
C++
438
Chapter 51. Check if it is possible to transform one string to another
Java
439
Chapter 51. Check if it is possible to transform one string to another
440
Chapter 51. Check if it is possible to transform one string to another
}
}
// This code is contributed by Nikita Tiwari.
Output:
YES
Source
https://www.geeksforgeeks.org/check-possible-transform-one-string-another/
441
Chapter 52
Input : N = 3, M = 3, K = 7
mat[][] = { { 2, 3, 1 },
{ 6, 1, 9 },
{ 8, 2, 3 } };
Output : 6
Path (1, 1) -> (2, 2) -> (3, 3) to complete
journey to absorb 6 value.
Input : N = 3, M = 4, K = 9
mat[][] = {
{ 2, 3, 4, 1 },
{ 6, 5, 5, 3 },
{ 5, 2, 3, 4 }
};
Output : -1
442
Chapter 52. Check if possible to cross the matrix with given power
• Declare a boolean 3D matrix, say dp[ ][ ][ ], with N*M*(K+1) dimension such that
dp[ i ][ j ][ k ] is true if it possible to reach the square in the ith row and jth column
with exactly k value collected so far.
• We can write the recurrence dp[ i ][ j ][ k ] = true if either
dp[i-1][j][k-mat[i][j]] or
dp[i][j-1][k-mat[i][j]] or
dp[i-1][j-1][k-mat[i][j]]
443
Chapter 52. Check if possible to cross the matrix with given power
if (k == grid[i][j])
dp[i][j][k] = true;
}
// For first cell of each row
else if (i == 0) {
dp[i][j][k] = (dp[i][j][k] ||
dp[i][j - 1][k - grid[i][j]]);
}
// For first cell of each column
else if (j == 0) {
dp[i][j][k] = (dp[i][j][k] ||
dp[i - 1][j][k - grid[i][j]]);
}
// For rest of the cell
else {
// Down movement.
dp[i][j][k] = (dp[i][j][k] ||
dp[i][j - 1][k - grid[i][j]]);
// Right movement.
dp[i][j][k] = (dp[i][j][k] ||
dp[i - 1][j][k - grid[i][j]]);
// Diagonal movement.
dp[i][j][k] = (dp[i][j][k] ||
dp[i - 1][j - 1][k - grid[i][j]]);
}
}
}
}
// Finding maximum k.
int ans = 0;
for (ans = k; ans >= 0; ans--)
if (dp[n - 1][m - 1][ans])
break;
return ans;
}
// Driver Code
int main()
{
int n = 3, m = 4, p = 9;
444
Chapter 52. Check if possible to cross the matrix with given power
int grid[R][C] = {
{ 2, 3, 4, 1 },
{ 6, 5, 5, 3 },
{ 5, 2, 3, 4 }
};
cout << maximumValue(n, m, p, grid) << endl;
return 0;
}
Java
445
Chapter 52. Check if possible to cross the matrix with given power
446
Chapter 52. Check if possible to cross the matrix with given power
{ 5, 2, 3, 4 }};
System.out.println(maximumValue(n, m, p, grid));
}
}
// This code is contributed by Anant Agarwal.
C#
// C# program to find if it
// is possible to cross the matrix
// with given power
using System;
class GFG {
static int N = 105;
// static int R = 3;
// static int C = 4;
static int maximumValue(int n, int m, int p,
int[, ] grid)
{
bool[,, ] dp = new bool[N, N, N];
int i, j, k;
// Initializing array dp with false value.
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
for (k = 0; k < N; k++)
dp[i, j, k] = false;
}
}
// For each value of dp[i][j][k]
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
for (k = grid[i, j]; k <= p; k++) {
// For first cell and for
// each value of k
if (i == 0 && j == 0) {
if (k == grid[i, j])
dp[i, j, k] = true;
}
// For first cell of each row
447
Chapter 52. Check if possible to cross the matrix with given power
else if (i == 0) {
dp[i, j, k] = (dp[i, j, k] ||
dp[i, j - 1, k - grid[i, j]]);
}
// For first cell of each column
else if (j == 0) {
dp[i, j, k] = (dp[i, j, k] ||
dp[i - 1, j, k - grid[i, j]]);
}
// For rest of the cell
else {
// Down movement.
dp[i, j, k] = (dp[i, j, k] ||
dp[i, j - 1, k - grid[i, j]]);
// Right movement.
dp[i, j, k] = (dp[i, j, k] ||
dp[i - 1, j, k - grid[i, j]]);
// Diagonal movement.
dp[i, j, k] = (dp[i, j, k] ||
dp[i - 1, j - 1, k - grid[i, j]]);
}
}
}
}
k = p;
// Finding maximum k.
int ans = 0;
for (ans = k; ans >= 0; ans--)
if (dp[n - 1, m - 1, ans])
break;
return ans;
}
// Driver code
public static void Main()
{
int n = 3, m = 4, p = 9;
int[, ] grid = { { 2, 3, 4, 1 },
{ 6, 5, 5, 3 },
{ 5, 2, 3, 4 } };
448
Chapter 52. Check if possible to cross the matrix with given power
Console.WriteLine(maximumValue(n, m, p, grid));
}
}
// This code is contributed by vt_m.
Output:
-1
Source
https://www.geeksforgeeks.org/check-possible-cross-matrix-given-power/
449
Chapter 53
Check whether row or column swaps produce maximum size binary sub-matrix with all 1s -
GeeksforGeeks
Given a binary matrix, the task is to find whether row swaps or column swaps give maximum
size sub-matrix with all 1’s. In a row swap, we are allowed to swap any two rows. In a
column swap we are allowed to swap any two columns. Output “Row Swap” or “Column
Swap” and the maximum size.
Examples:
Input : 1 1 1
1 0 1
Output : Column Swap
4
By swapping column 1 and column 2(0-based indexing),
index (0, 0) to (1, 1) makes the largest binary
sub-matrix.
Input : 0 0 0
1 1 0
1 1 0
0 0 0
1 1 0
Output : Row Swap
6
Input : 1 1 0
450
Chapter 53. Check whether row or column swaps produce maximum size binary sub-matrix
with all 1s
0 0 0
0 0 0
1 1 0
1 1 0
0 0 0
1 1 0
Output : Row Swap
8
The idea is to find both row swap and column swap maximum size binary submatrix and
compare.
To find the maximum sized binary sub-matrix with row swaps allowed, make a 2-D array,
say dp[i][j]. Each value of dp[i][j] contains the number of consecutive 1s on right side of (i,j)
in i-th row. Now, store each column in the 1-D temporary array one by one, say b[] and
sort, and find maximum b[i] * (n – i), since b[i] is indicating the sub-matrix width and (n –
i) is sub-matrix height.
Similarly, to find the maximum size binary sub-matrix with column swap allowed, find
dp[i][j], where each value contains the number of consecutive 1 below the (i, j) in j-th
column. Similarly, store each row in the 1-D temporary array one by one, say b[] and sort.
Find maximum b[i] * (m – i), since b[i] is indicating the submatrix height and (n – i) is
submatrix width.
Below is C++ implementation of this approach:
451
Chapter 53. Check whether row or column swaps produce maximum size binary sub-matrix
with all 1s
else
ryt[i][j] = ryt[i][j + 1] + 1;
}
}
// Travesing the 2d matrix from bottom-left.
for (int i = R - 1; i >= 0; i--)
{
for (int j = 0; j < C; ++j)
{
// If (i,j) contain 0, do nothing
if (mat[i][j] == 0)
dwn[i][j] = 0;
// Counting consecutive 1 down to (i,j).
else
dwn[i][j] = dwn[i + 1][j] + 1;
}
}
}
// Return maximum size submatrix with row swap allowed.
int solveRowSwap(int ryt[R + 2][C + 2])
{
int b[R] = { 0 }, ans = 0;
for (int j=0; j<C; j++)
{
// Copying the column
for (int i=0; i<R; i++)
b[i] = ryt[i][j];
// Sort the copied array
sort(b, b + R);
// Find maximum submatrix size.
for (int i = 0; i < R; ++i)
ans = max(ans, b[i] * (R - i));
}
return ans;
}
// Return maximum size submatrix with column
// swap allowed.
int solveColumnSwap(int dwn[R + 2][C + 2])
{
452
Chapter 53. Check whether row or column swaps produce maximum size binary sub-matrix
with all 1s
453
Chapter 53. Check whether row or column swaps produce maximum size binary sub-matrix
with all 1s
Output:
Row Swap
6
Source
https://www.geeksforgeeks.org/check-whether-row-column-swap-produces-maximum-size-binary-sub-matrix-1s/
454
Chapter 54
Choice of Area
This problem can be solved using recursion, after each time unit we can go to any of the
area but we will choose that area which ultimately leads to maximum survival time. As
455
Chapter 54. Choice of Area
recursion can lead to solving same subproblem many time, we will memoize the result on
basis of power A and B, if we reach to same pair of power A and B, we won’t solve it again
instead we will take the previously calculated result.
Given below is the simple implementation of above approach.
CPP
456
Chapter 54. Choice of Area
X, Y, Z, 3, memo));
break;
case 2:
temp = 1 + max(maxSurvival(A + X.a, B + X.b,
X, Y, Z, 1, memo),
maxSurvival(A + Z.a, B + Z.b,
X, Y, Z, 3, memo));
break;
case 3:
temp = 1 + max(maxSurvival(A + X.a, B + X.b,
X, Y, Z, 1, memo),
maxSurvival(A + Y.a, B + Y.b,
X, Y, Z, 2, memo));
break;
}
// store the result into map
memo[cur] = temp;
return temp;
}
// method returns maximum survival time
int getMaxSurvivalTime(int A, int B, area X, area Y, area Z)
{
if (A <= 0 || B <= 0)
return 0;
map< pair<int, int>, int > memo;
// At first, we can step into any of the area
return
max(maxSurvival(A + X.a, B + X.b, X, Y, Z, 1, memo),
maxSurvival(A + Y.a, B + Y.b, X, Y, Z, 2, memo),
maxSurvival(A + Z.a, B + Z.b, X, Y, Z, 3, memo));
}
// Driver code to test above method
int main()
{
area X(3, 2);
area Y(-5, -10);
area Z(-20, 5);
int A = 20;
int B = 8;
cout << getMaxSurvivalTime(A, B, X, Y, Z);
return 0;
457
Chapter 54. Choice of Area
Python3
458
Chapter 54. Choice of Area
Output:
Source
https://www.geeksforgeeks.org/game-theory-choice-area/
459
Chapter 55
Choose maximum weight with given weight and value ratio - GeeksforGeeks
Given weights and values of n items and a value k. We need to choose a subset of these
items in such a way that ratio of the sum of weight and sum of values of chosen items is K
and sum of weight is maximum among all possible subset choices.
We can solve this problem using dynamic programming. We can make a 2 state dp where
dp(i, j) will store maximum possible sum of weights under given conditions when total items
are N and required ratio is K.
Now in two states of dp, we will store the last item chosen and the difference between sum
of weight and sum of values. We will multiply item values by K so that second state of dp
will actually store (sum of weight – K*(sum of values)) for chosen items. Now we can see
that our answer will be stored in dp(N-1, 0) because as last item is (N-1)th so all items
are being considered and difference between sum of weight and K*(sum of values) is 0 that
means sum of weight and sum of values has a ratio K.
After defining above dp state we can write transition among states simply as shown below,
460
Chapter 55. Choose maximum weight with given weight and value ratio
In below code a top-down approach is used for solving this dynamic programming and for
storing dp states a map is used because the difference can be negative also and the 2D array
can create problem in that case and special care need to be taken.
C++
461
Chapter 55. Choose maximum weight with given weight and value ratio
Java
462
Chapter 55. Choose maximum weight with given weight and value ratio
return Integer.MIN_VALUE;
}
// first make pair with last chosen item and
// difference between weight and values
Point tmp = new Point(last, diff);
if (hm.containsKey(tmp))
return hm.get(tmp);
/* choose maximum value from following two
1) not selecting the current item and calling
recursively
2) selection current item, including the weight
and updating the difference before calling
recursively */
hm.put(tmp,Math.max(maxWeightRec(wt, val, K, hm, last - 1, diff),
wt[last] + maxWeightRec(wt, val, K, hm,
last - 1, diff + wt[last] - val[last] * K)));
return hm.get(tmp);
}
// method returns maximum sum of weight with K
// as ration of sum of weight and their values
static int maxWeight(int wt[], int val[], int K, int N)
{
HashMap<Point, Integer> hm = new HashMap<>();
return maxWeightRec(wt, val, K, hm, N - 1, 0);
}
// Driver method
public static void main(String args[])
{
int wt[] = {4, 8, 9};
int val[] = {2, 4, 6};
int K = 2;
System.out.println(maxWeight(wt, val, K, wt.length));
}
}
// This code is contributed by Gaurav Miglani
Output:
12
463
Chapter 55. Choose maximum weight with given weight and value ratio
Source
https://www.geeksforgeeks.org/choose-maximum-weight-given-weight-value-ratio/
464
Chapter 56
Clustering/Partitioning an
array such that sum of square
differences is minimum
ways to make clusters (partitions). We define a function Cost(i) for the cluster, as
the square of the difference between its first and last element. If the current cluster is
Examples :
465
Chapter 56. Clustering/Partitioning an array such that sum of square differences is
minimum
To solve the problem, we assume that we have k slabs. We have to insert them in some k
different positions in the array, which will give us the required partition scheme, and the
one having minimum value for f(x) will be the answer.
Naive solution:
If we solve the above problem by the naive method, we would simply take all the possibilities
and compute the minimum.
C++
466
Chapter 56. Clustering/Partitioning an array such that sum of square differences is
minimum
return;
// If we have mad k partitions and have
// reached last element
if (par==k && i==n-1)
{
ans = min(ans, current_ans);
return;
}
// 1) Partition array at different points
// 2) For every point, increase count of
// partitions, "par" by 1.
// 3) Before recursive call, add cost of
// the partition to current_ans
for (int j=i+1; j<n; j++)
solve(j, par+1, a, n, k, current_ans +
(a[j]-a[i+1])*(a[j]-a[i+1]));
}
// Driver code
int main()
{
int k = 2;
int a[] = {1, 5, 8, 10};
int n = sizeof(a)/sizeof(a[0]);
solve(-1, 0, a, n, k, 0);
cout << ans << endl;
return 0;
}
Java
467
Chapter 56. Clustering/Partitioning an array such that sum of square differences is
minimum
C#
468
Chapter 56. Clustering/Partitioning an array such that sum of square differences is
minimum
469
Chapter 56. Clustering/Partitioning an array such that sum of square differences is
minimum
Output:
20
Time Complexity: Its clear that the above algorithm has Time Complexity of .
Dynamic Programming:
We create a table dp[n+1][k+1] table and initialize all values as infinite.
Let us compute the value of dp[i][j]. we take an index m, such that m < i, and put a partition
next to that position such that there is no slab in between the indices i and m. It can be
seen simply that answer to the current scenario is dp[m][j-1] + (a[i-1]-a[m])*(a[i-1]-a[m]),
where the first term signifies the minimum f(x) till the element with j-1 partitions
and the second one signifies the cost of current cluster. So we will take the minimum of all
the possible indices m and dp[i][j] will be assigned the minimum amongst them.
C++
470
Chapter 56. Clustering/Partitioning an array such that sum of square differences is
minimum
// Current ending position (After i-th
// iteration result for a[0..i-1] is computed.
for (int i=1;i<=n;i++)
// j is number of partitions
for (int j=1;j<=k;j++)
// Picking previous partition for
// current i.
for (int m=i-1;m>=0;m--)
dp[i][j] = min(dp[i][j], dp[m][j-1] +
(a[i-1]-a[m])*(a[i-1]-a[m]));
return dp[n][k];
}
// Driver code
int main()
{
int k = 2;
int a[] = {1, 5, 8, 10};
int n = sizeof(a)/sizeof(a[0]);
cout << minCost(a, n, k) << endl;
return 0;
}
Java
471
Chapter 56. Clustering/Partitioning an array such that sum of square differences is
minimum
C#
472
Chapter 56. Clustering/Partitioning an array such that sum of square differences is
minimum
473
Chapter 56. Clustering/Partitioning an array such that sum of square differences is
minimum
// This code is contributed by nitin mittal
Output:
20
Time Complexity: Having the three simple loops, the complexity of the above algorithm
is .
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/clusteringpartitioning-an-array-such-that-sum-of-square-differences-is-minimum/
474
Chapter 57
Coin game winner where every player has three choices - GeeksforGeeks
A and B are playing a game. At the beginning there are n coins. Given two more numbers
x and y. In each move a player can pick x or y or l coins. A always starts the game. The
player who picks the last coin wins the game. For a given value of n, find whether A will
win the game or not if both are playing optimally.
Examples:
Input : n = 5, x = 3, y = 4
Output : A
There are 5 coins, every player can pick 1 or
3 or 4 coins on his/her turn.
A can win by picking 3 coins in first chance.
Now 2 coins will be left so B will pick one
coin and now A can win by picking the last coin.
Input : 2 3 4
Output : B
C++
475
Chapter 57. Coin game winner where every player has three choices
476
Chapter 57. Coin game winner where every player has three choices
Java
477
Chapter 57. Coin game winner where every player has three choices
int x = 3, y = 4, n = 5;
if (findWinner(x, y, n) == true)
System.out.println('A');
else
System.out.println('B');
}
}
// This code is contributed by Sumit Ghosh
Python3
478
Chapter 57. Coin game winner where every player has three choices
print('A')
else:
print('B')
# This code is contributed by Azkia Anam
C#
479
Chapter 57. Coin game winner where every player has three choices
PHP
<?php
// PHP program to find winner of game
// if player can pick 1, x, y coins
// To find winner of game
function findWinner( $x, $y, $n)
{
// To store results
$dp= array();
// Initial values
$dp[0] = false;
$dp[1] = true;
// Computing other values.
for ($i = 2; $i <= $n; $i++)
{
// If A losses any of i-1 or i-x
// or i-y game then he will
// definitely win game i
if ($i - 1 >= 0 and !$dp[$i - 1])
$dp[$i] = true;
else if ($i - $x >= 0 and !$dp[$i - $x])
$dp[$i] = true;
else if ($i - $y >= 0 and !$dp[$i - $y])
$dp[$i] = true;
480
Chapter 57. Coin game winner where every player has three choices
// Else A loses game.
else
$dp[$i] = false;
}
// If dp[n] is true then A will
// game otherwise he losses
return $dp[$n];
}
// Driver program to test findWinner();
$x = 3; $y = 4; $n = 5;
if (findWinner($x, $y, $n))
echo 'A';
else
echo 'B';
// This code is contributed by anuj_67.
?>
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/coin-game-winner-every-player-three-choices/
481
Chapter 58
1. Move one step ahead, i.e., cell (i, j-1) and direction remains left.
2. Move one step down and face right, i.e., cell (i+1, j) and direction becomes right.
Final position can be anywhere and final direction can also be anything. The target is to
collect maximum coins.
482
Chapter 58. Collect maximum coins before hitting a dead end
Example:
We strongly recommend you to minimize your browser and try this yourself
first.
The above problem can be recursively defined as below:
// Initialize result
If (arr[i][j] == 'C')
result = 1;
Else
result = 0;
If (d == 0) // Left direction
return result + max(maxCoins(i+1, j, 1), // Down
maxCoins(i, j-1, 0)); // Ahead in left
If (d == 1) // Right direction
483
Chapter 58. Collect maximum coins before hitting a dead end
484
Chapter 58. Collect maximum coins before hitting a dead end
};
// As per the question initial cell is (0, 0) and direction is
// right
cout << "Maximum number of collected coins is "
<< maxCoinsRec(arr, 0, 0, 1);
return 0;
}
Output:
The time complexity of above solution recursive is exponential. We can solve this problem
in Polynomial Time using Dynamic Programming. The idea is to use a 3 dimensional table
dp[R][C][k] where R is number of rows, C is number of columns and d is direction. Below
is Dynamic Programming based C++ implementation.
485
Chapter 58. Collect maximum coins before hitting a dead end
// Check if this cell contains the coin 'C' or if its 'E'.
dp[i][j][dir] = (arr[i][j] == 'C')? 1: 0;
// Get the maximum of two cases when you are facing right
// in this cell
if (dir == 1) // Direction is right
dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 0, dp), // Down
maxCoinsUtil(arr, i, j+1, 1, dp)); // Ahead in rught
// Get the maximum of two cases when you are facing left
// in this cell
if (dir == 0) // Direction is left
dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 1, dp), // Down
maxCoinsUtil(arr, i, j-1, 0, dp)); // Ahead in left
// return the answer
return dp[i][j][dir];
}
// This function mainly creates a lookup table and calls
// maxCoinsUtil()
int maxCoins(char arr[R][C])
{
// Create lookup table and initialize all values as -1
int dp[R][C][2];
memset(dp, -1, sizeof dp);
// As per the question initial cell is (0, 0) and direction
// is right
return maxCoinsUtil(arr, 0, 0, 1, dp);
}
// Driver program to test above function
int main()
{
char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'},
{'C', '#', 'C', '#', 'E'},
{'#', 'C', 'C', '#', 'C'},
{'C', 'E', 'E', 'C', 'E'},
{'C', 'E', '#', 'C', 'E'}
};
cout << "Maximum number of collected coins is "
<< maxCoins(arr);
return 0;
486
Chapter 58. Collect maximum coins before hitting a dead end
Output:
Time Complexity of above solution is O(R x C x d). Since d is 2, time complexity can be
written as O(R x C).
Thanks to Gaurav Ahirwar for suggesting above solution.
Source
https://www.geeksforgeeks.org/collect-maximum-coins-before-hitting-a-dead-end/
487
Chapter 59
Input :
int arr[R][C] = {{3, 6, 8, 2},
{5, 2, 4, 3},
{1, 1, 20, 10},
{1, 1, 20, 10},
{1, 1, 20, 10},
};
Output: 73
Explanation :
488
Chapter 59. Collect maximum points in a grid using two traversals
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to do both traversals concurrently. We start first from (0, 0) and second traversal
from (0, C-1) simultaneously. The important thing to note is, at any particular step both
traversals will be in same row as in all possible three moves, row number is increased. Let
(x1, y1) and (x2, y2) denote current positions of first and second traversals respectively.
Thus at any time x1 will be equal to x2 as both of them move forward but variation is
possible along y. Since variation in y could occur in 3 ways no change (y), go left (y – 1),
go right (y + 1). So in total 9 combinations among y1, y2 are possible. The 9 cases as
mentioned below after base cases.
// If both traversals are at same cell, then we count the value of cell
// only once.
If y1 and y2 are same
result = arr[x][y1]
Else
result = arr[x][y1] + arr[x][y2]
The above recursive solution has many subproblems that are solved again and again. There-
fore, we can use Dynamic Programming to solve the above problem more efficiently. Below
is memoization (Memoization is alternative to table based iterative solution in Dynamic Pro-
489
Chapter 59. Collect maximum points in a grid using two traversals
490
Chapter 59. Collect maximum points in a grid using two traversals
Output:
Maximum collection is 73
Source
https://www.geeksforgeeks.org/collect-maximum-points-in-a-grid-using-two-traversals/
491
Chapter 60
Example:
Input: n = 10, r = 2, p = 13
Output: 6
Explanation: 10C2 is 45 and 45 % 13 is 6.
492
Chapter 60. Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
The above formula can implemented using Dynamic Programming using a 2D array.
The 2D array based dynamic programming solution can be further optimized by constructing
one row at a time. See Space optimized version in below post for details.
Binomial Coefficient using Dynamic Programming
Below is implementation based on the space optimized version discussed in above post.
C++
493
Chapter 60. Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
JAVA
494
Chapter 60. Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
return C[r];
}
// Driver program
public static void main(String args[])
{
int n = 10, r = 2, p = 13;
System.out.println("Value of nCr % p is "
+ nCrModp(n, r, p));
}
}
// This code is contributed by Nikita Tiwari.
Python3
495
Chapter 60. Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
# This code is contributed by Soumen Ghosh
C#
496
Chapter 60. Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
[
PHP
<?php
// A Dynamic Programming based
// solution to compute nCr % p
// Returns nCr % p
function nCrModp($n, $r, $p)
{
// The array C is going
// to store last row of
// pascal triangle at
// the end. And last entry
// of last row is nCr
$C = array();
for( $i = 0; $i < $r + 1; $i++)
$C[$i] = 0;
// Top row of Pascal
// Triangle
$C[0] = 1;
// One by constructs remaining
// rows of Pascal Triangle from
// top to bottom
for ($i = 1; $i <= $n; $i++)
{
// Fill entries of current
// row using previous row values
for ($j = Min($i, $r); $j > 0; $j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
$C[$j] = ($C[$j] +
$C[$j - 1]) % $p;
}
497
Chapter 60. Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
return $C[$r];
}
// Driver Code
$n = 10; $r = 2;$p = 13;
echo "Value of nCr % p is " ,
nCrModp($n, $r, $p);
// This code is contributed
// by anuj_67.
?>
Output:
Value of nCr % p is 6
Time complexity of above solution is O(n*r) and it requires O(n) space. There are more
and better solutions to above problem.
Compute nCr % p | Set 2 (Lucas Theorem)
Improved By : nitin mittal, vt_m
Source
https://www.geeksforgeeks.org/compute-ncr-p-set-1-introduction-and-dynamic-programming-solution/
498
Chapter 61
Input: n = 5
Output: Sum of digits in numbers from 1 to 5 = 15
Input: n = 12
Output: Sum of digits in numbers from 1 to 12 = 51
Input: n = 328
Output: Sum of digits in numbers from 1 to 328 = 3241
Naive Solution:
A naive solution is to go through every number x from 1 to n, and compute sum in x by
traversing all digits of x. Below is the implementation of this idea.
C++
499
Chapter 61. Compute sum of digits in all numbers from 1 to n
{
int result = 0; // initialize result
// One by one compute sum of digits in every number from
// 1 to n
for (int x = 1; x <= n; x++)
result += sumOfDigits(x);
return result;
}
// A utility function to compute sum of digits in a
// given number x
int sumOfDigits(int x)
{
int sum = 0;
while (x != 0)
{
sum += x %10;
x = x /10;
}
return sum;
}
// Driver Program
int main()
{
int n = 328;
cout << "Sum of digits in numbers from 1 to " << n << " is "
<< sumOfDigitsFrom1ToN(n);
return 0;
}
Java
500
Chapter 61. Compute sum of digits in all numbers from 1 to n
Python3
501
Chapter 61. Compute sum of digits in all numbers from 1 to n
return result
# A utility function to compute sum of
# digits in a given number x
def sumOfDigits(x) :
sum = 0
while (x != 0) :
sum = sum + x % 10
x = x // 10
return sum
# Driver Program
n = 328
print("Sum of digits in numbers from 1 to", n, "is", sumOfDigitsFrom1ToN(n))
# This code is contributed by Nikita Tiwari.
C#
502
Chapter 61. Compute sum of digits in all numbers from 1 to n
{
int sum = 0;
while (x != 0)
{
sum += x % 10;
x = x / 10;
}
return sum;
}
// Driver Program
public static void Main()
{
int n = 328;
Console.WriteLine("Sum of digits"
+ " in numbers from 1 to "
+ n + " is "
+ sumOfDigitsFrom1ToN(n));
}
}
// This code is contributed by shiv_bhakt.
PHP
<?php
// A Simple php program to compute sum
//of digits in numbers from 1 to n
// Returns sum of all digits in
// numbers from 1 to n
function sumOfDigitsFrom1ToN($n)
{
$result = 0; // initialize result
// One by one compute sum of digits
// in every number from 1 to n
for ($x = 1; $x <= $n; $x++)
$result += sumOfDigits($x);
return $result;
}
// A utility function to compute sum
503
Chapter 61. Compute sum of digits in all numbers from 1 to n
Output
Efficient Solution:
Above is a naive solution. We can do it more efficiently by finding a pattern.
Let us take few examples.
sum(9) = 1 + 2 + 3 + 4 ........... + 9
= 9*10/2
= 45
504
Chapter 61. Compute sum of digits in all numbers from 1 to n
C++
505
Chapter 61. Compute sum of digits in all numbers from 1 to n
506
Chapter 61. Compute sum of digits in all numbers from 1 to n
Java
507
Chapter 61. Compute sum of digits in all numbers from 1 to n
Python3
508
Chapter 61. Compute sum of digits in all numbers from 1 to n
# d = number of digits minus one in n.
# For 328, d is 2
d = (int)(math.log10(n))
"""computing sum of digits from 1 to 10^d-1,
d=1 a[0]=0;
d=2 a[1]=sum of digit from 1 to 9 = 45
d=3 a[2]=sum of digit from 1 to 99 = a[1]*10
+ 45*10^1 = 900
d=4 a[3]=sum of digit from 1 to 999 = a[2]*10
+ 45*10^2 = 13500"""
a = [0] * (d + 1)
a[0] = 0
a[1] = 45
for i in range(2, d+1) :
a[i] = a[i-1] * 10 + 45 * (int)(math.ceil(math.pow(10,i-1)))
# computing 10^d
p = (int)(math.ceil(math.pow(10, d)))
# Most significant digit (msd) of n,
# For 328, msd is 3 which can be obtained
# using 328/100
msd = n//p
"""EXPLANATION FOR FIRST and SECOND TERMS IN
BELOW LINE OF CODE
First two terms compute sum of digits from 1 to 299
(sum of digits in range 1-99 stored in a[d]) +
(sum of digits in range 100-199, can be calculated
as 1*100 + a[d]. (sum of digits in range 200-299,
can be calculated as 2*100 + a[d]
The above sum can be written as 3*a[d] + (1+2)*100
EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW
LINE OF CODE
The last two terms compute sum of digits in number
from 300 to 328. The third term adds 3*29 to sum
as digit 3 occurs in all numbers from 300 to 328.
The fourth term recursively calls for 28"""
return (int)(msd * a[d] + (msd*(msd-1) // 2) * p +
msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p))
# Driver Program
n = 328
print("Sum of digits in numbers from 1 to",
n ,"is",sumOfDigitsFrom1ToN(n))
509
Chapter 61. Compute sum of digits in all numbers from 1 to n
# This code is contributed by Nikita Tiwari.
C#
510
Chapter 61. Compute sum of digits in all numbers from 1 to n
int msd = n / p;
// EXPLANATION FOR FIRST and SECOND TERMS IN
// BELOW LINE OF CODE
// First two terms compute sum of digits from
// 1 to 299
// (sum of digits in range 1-99 stored in a[d]) +
// (sum of digits in range 100-199, can be
// calculated as 1*100 + a[d]
// (sum of digits in range 200-299, can be
// calculated as 2*100 + a[d]
// The above sum can be written as 3*a[d] +
// (1+2)*100
// EXPLANATION FOR THIRD AND FOURTH TERMS IN
// BELOW LINE OF CODE
// The last two terms compute sum of digits in
// number from 300 to 328. The third term adds
// 3*29 to sum as digit 3 occurs in all numbers
// from 300 to 328. The fourth term recursively
// calls for 28
return (msd * a[d] + (msd * (msd - 1) / 2) * p +
msd * (1 + n % p) + sumOfDigitsFrom1ToN(n % p));
}
// Driver Program
public static void Main()
{
int n = 328;
Console.WriteLine("Sum of digits in numbers " +
"from 1 to " +n + " is " +
sumOfDigitsFrom1ToN(n));
}
}
// This code is contributed by shiv_bhakt.
Output
The efficient algorithm has one more advantage that we need to compute the array ‘a[]’ only
once even when we are given multiple inputs.
This article is computed by Shubham Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : shiv_bhakt, jit_t
511
Chapter 61. Compute sum of digits in all numbers from 1 to n
Source
https://www.geeksforgeeks.org/count-sum-of-digits-in-numbers-from-1-to-n/
512
Chapter 62
Construction of Longest
Increasing Subsequence using
Dynamic Programming
In previous post, we have discussed about Longest Increasing Subsequence problem. How-
ever, the post only covered code related to querying size of LIS, but not the construction
of LIS. In this post, we will discuss how to print LIS using similar DP solution discussed
earlier.
Let arr[0..n-1] be the input array. We define vector L such that L[i] is itself is a vector that
stores LIS of arr that ends with arr[i]. For example, for array [3, 2, 6, 4, 5, 1],
L[0]: 3
L[1]: 2
L[2]: 2 6
L[3]: 2 4
L[4]: 2 4 5
L[5]: 1
513
Chapter 62. Construction of Longest Increasing Subsequence using Dynamic Programming
L[0] = {arr[O]}
L[i] = {Max(L[j])} + arr[i]
where j < i and arr[j] < arr[i] and if there is no such j then L[i] = arr[i]
514
Chapter 62. Construction of Longest Increasing Subsequence using Dynamic Programming
Output:
2 4 5
Note that the time complexity of the above Dynamic Programming (DP) solution is O(n^2)
and there is a O(n Log n) non-DP solution for the LIS problem. See below post for O(n
Log n) solution.
Construction of Longest Monotonically Increasing Subsequence (N log N)
Source
https://www.geeksforgeeks.org/construction-of-longest-increasing-subsequence-using-dynamic-programming/
515
Chapter 63
Input : arr[] = { 1, 2, 6, 5, 4}
Output : 2
We can a[2] to any value between 2 and 5
and a[4] to any value greater then 5.
Input : arr[] = { 1, 2, 3, 5, 7, 11 }
Output : 0
Array is already strictly increasing.
The problem is variation of Longest Increasing Subsequence. The numbers which are already
a part of LIS need not to be changed. So minimum elements to change is difference of size
of array and number of elements in LIS.
C++
516
Chapter 63. Convert to Strictly increasing array with minimum changes
Java
517
Chapter 63. Convert to Strictly increasing array with minimum changes
LCS[i] = 1;
// Find LCS of array
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (arr[i] > arr[j])
LCS[i] = Math.max(LCS[i],
LCS[j] + 1);
}
len = Math.max(len, LCS[i]);
}
// Return min changes for array
// to strictly increasing
return n - len;
}
// Driver program to test minRemove()
public static void main(String[] args)
{
int arr[] = { 1, 2, 6, 5, 4 };
int n = arr.length;
System.out.println(minRemove(arr, n));
}
}
Python3
518
Chapter 63. Convert to Strictly increasing array with minimum changes
len = max(len, LCS[i])
# Return min changes for array
# to strictly increasing
return (n - len)
# Driver Code
arr = [ 1, 2, 6, 5, 4 ]
n = len(arr)
print(minRemove(arr, n))
# This code is contributed by Azkia Anam.
C#
519
Chapter 63. Convert to Strictly increasing array with minimum changes
PHP
<?php
// PHP program to find min
// elements to change so
// array is strictly increasing
// To find min elements to
// remove from array to make
// it strictly increasing
function minRemove($arr, $n)
{
$LCS = array();
$len = 0;
// Mark all elements
// of LCS as 1
for ($i = 0; $i < $n; $i++)
$LCS[$i] = 1;
// Find LCS of array
for ($i = 1; $i < $n; $i++)
{
for ($j = 0; $j < $i; $j++)
{
if ($arr[$i] > $arr[$j])
520
Chapter 63. Convert to Strictly increasing array with minimum changes
$LCS[$i] = max($LCS[$i],
$LCS[$j] + 1);
}
$len = max($len, $LCS[$i]);
}
// Return min changes
// for array to strictly
// increasing
return $n - $len;
}
// Driver Code
$arr = array(1, 2, 6, 5, 4);
$n = count($arr);
echo minRemove($arr, $n);
// This code is contributed
// by anuj_6
?>
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/convert-strictly-increasing-array-minimum-changes/
521
Chapter 64
Input: n = 5
Output: 1
Only 4 has '4' as digit
Input: n = 50
Output: 14
Input: n = 328
Output: 60
This problem is mainly a variation of previous article on Compute sum of digits in all
numbers from 1 to n.
Naive Solution:
A naive solution is to go through every number x from 1 to n, and check if x has 4. To check
if x has or not, we can traverse all digits of x. Below is the implementation of above idea :
Source
https://www.geeksforgeeks.org/count-numbers-from-1-to-n-that-have-4-as-a-a-digit/
C++
522
Chapter 64. Count numbers from 1 to n that have 4 as a digit
Java
523
Chapter 64. Count numbers from 1 to n that have 4 as a digit
class GFG {
// Returns sum of all digits
// in numbers from 1 to n
static int countNumbersWith4(int n)
{
// initialize result
int result = 0;
// One by one compute sum of digits
// in every number from 1 to n
for (int x=1; x<=n; x++)
result += has4(x)? 1 : 0;
return result;
}
// A utility function to compute sum
// of digits in a given number x
static boolean has4(int x)
{
while (x != 0)
{
if (x%10 == 4)
return true;
x = x /10;
}
return false;
}
// Driver Program
public static void main(String args[])
{
int n = 328;
System.out.println("Count of numbers from 1 to "
+ " that have 4 as a a digit is "
+ countNumbersWith4(n)) ;
}
}
// This code is contributed by Nikita Tiwari.
Python
524
Chapter 64. Count numbers from 1 to n that have 4 as a digit
def countNumbersWith4(n) :
result = 0 # initialize result
# One by one compute sum of digits
# in every number from 1 to n
for x in range(1, n + 1) :
if(has4(x) == True) :
result = result + 1
return result
# A utility function to compute sum
# of digits in a given number x
def has4(x) :
while (x != 0) :
if (x%10 == 4) :
return True
x = x //10
return False
# Driver Program
n = 328
print ("Count of numbers from 1 to ", n,
" that have 4 as a a digit is ",
countNumbersWith4(n))
# This code is contributed by Nikita Tiwari.
C#
525
Chapter 64. Count numbers from 1 to n that have 4 as a digit
PHP
<?php
// PHP program to compute sum of
// digits in numbers from 1 to n
// Returns sum of all digits
// in numbers from 1 to n
function countNumbersWith4($n)
{
$result = 0; // initialize result
// One by one compute sum of
// digits in every number from 1 to n
for ($x = 1; $x <= $n; $x++)
$result += has4($x) ? 1 : 0;
526
Chapter 64. Count numbers from 1 to n that have 4 as a digit
return $result;
}
// A utility function to compute
// sum of digits in a given number x
function has4($x)
{
while ($x != 0)
{
if ($x % 10 == 4)
return true;
$x = intval($x / 10);
}
return false;
}
// Driver Code
$n = 328;
echo "Count of numbers from 1 to " . $n .
" that have 4 as a a digit is " .
countNumbersWith4($n);
// This code is contributed by Sam007
?>
Output :
Efficient Solution:
Above is a naive solution. We can do it more efficiently by finding a pattern.
Let us take few examples.
527
Chapter 64. Count numbers from 1 to n that have 4 as a digit
528
Chapter 64. Count numbers from 1 to n that have 4 as a digit
// d=3 a[3] = count of numbers from 0 to 999 = a[2]*19 + 100 = 171
int *a = new int[d+1];
a[0] = 0, a[1] = 1;
for (int i=2; i<=d; i++)
a[i] = a[i-1]*9 + ceil(pow(10,i-1));
// Computing 10^d
int p = ceil(pow(10, d));
// Most significant digit (msd) of n,
// For 328, msd is 3 which can be obtained using 328/100
int msd = n/p;
// If MSD is 4. For example if n = 428, then count of
// numbers is sum of following.
// 1) Count of numbers from 1 to 399
// 2) Count of numbers from 400 to 428 which is 29.
if (msd == 4)
return (msd)*a[d] + (n%p) + 1;
// IF MSD > 4. For example if n is 728, then count of
// numbers is sum of following.
// 1) Count of numbers from 1 to 399 and count of numbers
// from 500 to 699, i.e., "a[2] * 6"
// 2) Count of numbers from 400 to 499, i.e. 100
// 3) Count of numbers from 700 to 728, recur for 28
if (msd > 4)
return (msd-1)*a[d] + p + countNumbersWith4(n%p);
// IF MSD < 4. For example if n is 328, then count of
// numbers is sum of following.
// 1) Count of numbers from 1 to 299 a
// 2) Count of numbers from 300 to 328, recur for 28
return (msd)*a[d] + countNumbersWith4(n%p);
}
// Driver Program
int main()
{
int n = 328;
cout << "Count of numbers from 1 to " << n
<< " that have 4 as a a digit is "
<< countNumbersWith4(n) << endl;
return 0;
}
Output:
529
Chapter 64. Count numbers from 1 to n that have 4 as a digit
This article is contributed by Shivam. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : Sam007
530
Chapter 65
CountPS(i, j)
531
Chapter 65. Count All Palindrome Sub-Strings in a String | Set 1
If we draw recursion tree of above recursive solution, we can observe overlapping Subprolems.
Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic
Programming. Below is Dynamic Programming based solution.
C/C++
532
Chapter 65. Count All Palindrome Sub-Strings in a String | Set 1
P[i][i] = true;
// palindrome of length 2
for (int i=0; i<n-1; i++)
{
if (str[i] == str[i+1])
{
P[i][i+1] = true;
dp[i][i+1] = 1 ;
}
}
// Palindromes of length more then 2. This loop is similar
// to Matrix Chain Multiplication. We start with a gap of
// length 2 and fill DP table in a way that gap between
// starting and ending indexes increases one by one by
// outer loop.
for (int gap=2 ; gap<n; gap++)
{
// Pick starting point for current gap
for (int i=0; i<n-gap; i++)
{
// Set ending point
int j = gap + i;
// If current string is palindrome
if (str[i] == str[j] && P[i+1][j-1] )
P[i][j] = true;
// Add current palindrome substring ( + 1)
// and rest palinrome substring (dp[i][j-1] + dp[i+1][j])
// remove common palinrome substrings (- dp[i+1][j-1])
if (P[i][j] == true)
dp[i][j] = dp[i][j-1] + dp[i+1][j] + 1 - dp[i+1][j-1];
else
dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1];
}
}
// return total palindromic substrings
return dp[0][n-1];
}
// Driver program
int main()
{
char str[] = "abaab";
int n = strlen(str);
533
Chapter 65. Count All Palindrome Sub-Strings in a String | Set 1
Java
534
Chapter 65. Count All Palindrome Sub-Strings in a String | Set 1
int j = gap + i;
// If current string is palindrome
if (str[i] == str[j] && P[i+1][j-1] )
P[i][j] = true;
// Add current palindrome substring ( + 1)
// and rest palinrome substring (dp[i][j-1] + dp[i+1][j])
// remove common palinrome substrings (- dp[i+1][j-1])
if (P[i][j] == true)
dp[i][j] = dp[i][j-1] + dp[i+1][j] + 1 - dp[i+1][j-1];
else
dp[i][j] = dp[i][j-1] + dp[i+1][j] - dp[i+1][j-1];
}
}
// return total palindromic substrings
return dp[0][n-1];
}
// Driver Method
public static void main(String[] args)
{
String str = "abaab";
System.out.println(CountPS(str.toCharArray(), str.length()));
}
}
Output:
Source
https://www.geeksforgeeks.org/count-palindrome-sub-strings-string/
535
Chapter 66
CountPS(i,j)
// Every single character of a string is a palindrome
// subsequence
if i == j
return 1 // palindrome of length 1
536
Chapter 66. Count All Palindromic Subsequence in a given String
else
// check for rest sub-sequence and remove common
// palindromic subsequences as they are counted
// twice when we do countPS(i+1, j) + countPS(i,j-1)
return countPS(i+1, j) + countPS(i, j-1) - countPS(i+1, j-1)
If we draw recursion tree of above recursive solution, we can observe overlapping Subpro-
lems. Since the problem has overlapping subproblems, we can solve it efficiently using
Dynamic Programming. Below is Dynamic Programming based solution.
C++
537
Chapter 66. Count All Palindromic Subsequence in a given String
cps[i][k] = cps[i][k-1] +
cps[i+1][k] -
cps[i+1][k-1];
}
}
// return total palindromic subsequence
return cps[0][N-1];
}
// Driver program
int main()
{
string str = "abcb";
cout << "Total palindromic subsequence are : "
<< countPS(str) << endl;
return 0;
}
Java
538
Chapter 66. Count All Palindromic Subsequence in a given String
cps[i][k] = cps[i][k-1] +
cps[i+1][k] + 1;
else
cps[i][k] = cps[i][k-1] +
cps[i+1][k] -
cps[i+1][k-1];
}
}
}
// return total palindromic subsequence
return cps[0][N-1];
}
// Driver program
public static void main(String args[])
{
String str = "abcb";
System.out.println("Total palindromic "+
"subsequence are : "
+ countPS(str));
}
}
// This code is contributed by Sumit Ghosh
Python3
539
Chapter 66. Count All Palindromic Subsequence in a given String
for i in range(N):
k = L + i - 1
if (k < N):
if (str[i] == str[k]):
cps[i][k] = (cps[i][k - 1] +
cps[i + 1][k] + 1)
else:
cps[i][k] = (cps[i][k - 1] +
cps[i + 1][k] -
cps[i + 1][k - 1])
# return total palindromic subsequence
return cps[0][N - 1]
# Driver program
str = "abcb"
print("Total palindromic subsequence are : "
, countPS(str))
# This code is contributed by Anant Agarwal.
C#
540
Chapter 66. Count All Palindromic Subsequence in a given String
{
for (int i = 0; i < N; i++)
{
int k = L + i - 1;
if (k < N) {
if (str[i] == str[k])
cps[i, k] = cps[i, k - 1] +
cps[i + 1, k] + 1;
else
cps[i, k] = cps[i, k - 1] +
cps[i + 1, k] -
cps[i + 1, k - 1];
}
}
}
// return total palindromic
// subsequence
return cps[0, N - 1];
}
// Driver Code
public static void Main()
{
string str = "abcb";
Console.Write("Total palindromic "+
"subsequence are : "
+ countPS(str));
}
}
// This code is contributed by nitin mittal.
Output:
Source
https://www.geeksforgeeks.org/count-palindromic-subsequence-given-string/
541
Chapter 67
Input : h = 3
Output : 15
Input : h = 4
Output : 315
542
Chapter 67. Count Balanced Binary Trees of Height h
1. (h-1), (h-2)
2. (h-2), (h-1)
3. (h-1), (h-1)
Hence we can see that the problem has optimal substructure property.
A recursive function to count no of balanced binary trees of height h is:
int countBT(int h)
{
// One tree is possible with height 0 or 1
if (h == 0 || h == 1)
return 1;
return countBT(h-1) * (2 *countBT(h-2) +
countBT(h-1));
}
The time complexity of this recursive approach will be exponential. The recursion tree for
the problem with h = 3 looks like :
As we can see, sub-problems are solved repeatedly. Therefore we store the results as we
compute them.
An efficient dynamic programming approach will be as follows :
CPP
543
Chapter 67. Count Balanced Binary Trees of Height h
PHP
<?php
// PHP program to count
// number of balanced
$mod =1000000007;
function countBT($h)
{
global $mod;
// base cases
$dp[0] = $dp[1] = 1;
for($i = 2; $i <= $h; $i++)
{
$dp[$i] = ($dp[$i - 1] *
((2 * $dp [$i - 2]) %
$mod + $dp[$i - 1]) %
$mod) % $mod;
}
return $dp[$h];
}
// Driver Code
$h = 3;
544
Chapter 67. Count Balanced Binary Trees of Height h
Output :
Source
https://www.geeksforgeeks.org/count-balanced-binary-trees-height-h/
545
Chapter 68
Count Derangements
(Permutation such that no
element appears in its original
position)
Count Derangements (Permutation such that no element appears in its original position) -
GeeksforGeeks
A Derangement is a permutation of n elements, such that no element appears in its original
position. For example, a derangement of {0, 1, 2, 3} is {2, 3, 1, 0}.
Given a number n, find total number of Derangements of a set of n elements.
Examples :
Input: n = 2
Output: 1
For two elements say {0, 1}, there is only one
possible derangement {1, 0}
Input: n = 3
Output: 2
For three elements say {0, 1, 2}, there are two
possible derangements {2, 0, 1} and {1, 2, 0}
Input: n = 4
Output: 9
For four elements say {0, 1, 2, 3}, there are 9
possible derangements {1, 0, 3, 2} {1, 2, 3, 0}
546
Chapter 68. Count Derangements (Permutation such that no element appears in its
original position)
Let countDer(n) be count of derangements for n elements. Below is recursive relation for it.
1. i is placed at 0: This case is equivalent to solving the problem for n-2 elements as
two elements have just swapped their positions.
2. i is not placed at 0: This case is equivalent to solving the problem for n-1 elements
as now there are n-1 elements, n-1 positions and every element has n-2 choices
C++
547
Chapter 68. Count Derangements (Permutation such that no element appears in its
original position)
Java
Python3
548
Chapter 68. Count Derangements (Permutation such that no element appears in its
original position)
C#
// A Naive Recursive C#
// program to count derangements
using System;
class GFG
{
// Function to count
// derangements
static int countDer(int n)
{
// Base cases
if (n == 1) return 0;
if (n == 0) return 1;
if (n == 2) return 1;
// countDer(n) = (n-1)[countDer(n-1) + der(n-2)]
return (n - 1) * (countDer(n - 1) +
countDer(n - 2));
}
// Driver Code
public static void Main ()
{
int n = 4;
Console.Write( "Count of Derangements is " +
countDer(n));
}
}
// This code is contributed by nitin mittal.
PHP
549
Chapter 68. Count Derangements (Permutation such that no element appears in its
original position)
<?php
// A Naive Recursive PHP program
// to count derangements
function countDer($n)
{
// Base cases
if ($n == 1)
return 0;
if ($n == 0)
return 1;
if ($n == 2)
return 1;
// countDer(n) = (n-1)[countDer(n-1) +
// der(n-2)]
return ($n - 1) * (countDer($n - 1) +
countDer($n - 2));
}
// Driver Code
$n = 4;
echo "Count of Derangements is ", countDer($n);
// This code is contributed by nitin mittal.
?>
Output:
Count of Derangements is 9
cdr(5)
/ \
cdr(4) cdr(3)
/ \ / \
cdr(3) cdr(2) cdr(2) cdr(1)
550
Chapter 68. Count Derangements (Permutation such that no element appears in its
original position)
C++
Java
551
Chapter 68. Count Derangements (Permutation such that no element appears in its
original position)
// derangements
static int countDer(int n)
{
// Create an array to store
// counts for subproblems
int der[] = new int[n + 1];
// Base cases
der[0] = 1;
der[1] = 0;
der[2] = 1;
// Fill der[0..n] in bottom up
// manner using above recursive
// formula
for (int i = 3; i <= n; ++i)
der[i] = (i - 1) * (der[i - 1] +
der[i - 2]);
// Return result for n
return der[n];
}
// Driver program
public static void main (String[] args)
{
int n = 4;
System.out.println("Count of Derangements is " +
countDer(n));
}
}
// This code is contributed by vt_m
Python3
552
Chapter 68. Count Derangements (Permutation such that no element appears in its
original position)
der[1] = 0
der[2] = 1
# Fill der[0..n] in bottom up manner
# using above recursive formula
for i in range(3, n + 1):
der[i] = (i - 1) * (der[i - 1] +
der[i - 2])
# Return result for n
return der[n]
# Driver Code
n = 4
print("Count of Derangements is ", countDer(n))
# This code is contributed by Azkia Anam.
C#
// A Dynamic programming based
// C# program to count derangements
using System;
class GFG
{
// Function to count
// derangements
static int countDer(int n)
{
// Create an array to store
// counts for subproblems
int []der = new int[n + 1];
// Base cases
der[0] = 1;
der[1] = 0;
der[2] = 1;
// Fill der[0..n] in bottom up
// manner using above recursive
// formula
for (int i = 3; i <= n; ++i)
der[i] = (i - 1) * (der[i - 1] +
der[i - 2]);
553
Chapter 68. Count Derangements (Permutation such that no element appears in its
original position)
PHP
<?php
// A Dynamic programming based PHP
// program to count derangements
function countDer($n)
{
// Create an array to store
// counts for subproblems
// Base cases
$der[0] = 1;
$der[1] = 0;
$der[2] = 1;
// Fill der[0..n] in bottom up manner
// using above recursive formula
for ($i = 3; $i <= $n; ++$i)
$der[$i] = ($i - 1) * ($der[$i - 1] +
$der[$i - 2]);
// Return result for n
return $der[$n];
}
// Driver code
$n = 4;
echo "Count of Derangements is ",
countDer($n);
// This code is contributed by aj_36
554
Chapter 68. Count Derangements (Permutation such that no element appears in its
original position)
?>
Output :
Count of Derangements is 9
Source
https://www.geeksforgeeks.org/count-derangements-permutation-such-that-no-element-appears-in-its-original-posit
555
Chapter 69
The problem of counting distinct subsequences is easy if all characters of input string are
distinct. The count is equal to n C0 + n C1 + n C2 + … n Cn = 2n .
How to count distinct subsequences when there can be repetition in input string?
A Simple Solution to count distinct subsequences in a string with duplicates is to generate
all subsequences. For every subsequence, store it in a hash table if it doesn’t exist already.
Time complexity of this solution is exponential and it requires exponential extra space.
An Efficient Solution doesn’t require generation of subsequences.
556
Chapter 69. Count Distinct Subsequences
Else:
Repetition = Count(m)
Here m is index of previous occurrence of
current character. We basically remove all
counts ending with previous occurrence of
current character.
C++
557
Chapter 69. Count Distinct Subsequences
dp[0] = 1;
// Traverse through all lengths from 1 to n.
for (int i=1; i<=n; i++)
{
// Number of subsequences with substring
// str[0..i-1]
dp[i] = 2*dp[i-1];
// If current character has appeared
// before, then remove all subsequences
// ending with previous occurrence.
if (last[str[i-1]] != -1)
dp[i] = dp[i] - dp[last[str[i-1]]];
// Mark occurrence of current character
last[str[i-1]] = (i-1);
}
return dp[n];
}
// Driver code
int main()
{
cout << countSub("gfg");
return 0;
}
Java
558
Chapter 69. Count Distinct Subsequences
int n = str.length();
// dp[i] is going to store count of distinct
// subsequences of length i.
int[] dp = new int[n+1];
// Empty substring has only one subsequence
dp[0] = 1;
// Traverse through all lengths from 1 to n.
for (int i=1; i<=n; i++)
{
// Number of subsequences with substring
// str[0..i-1]
dp[i] = 2*dp[i-1];
// If current character has appeared
// before, then remove all subsequences
// ending with previous occurrence.
if (last[(int)str.charAt(i-1)] != -1)
dp[i] = dp[i] - dp[last[(int)str.charAt(i-1)]];
// Mark occurrence of current character
last[(int)str.charAt(i-1)] = (i-1);
}
return dp[n];
}
// Driver code
public static void main(String args[])
{
System.out.println(countSub("gfg"));
}
}
// This code is contributed by Sumit Ghosh
Output:
559
Chapter 69. Count Distinct Subsequences
Source
https://www.geeksforgeeks.org/count-distinct-subsequences/
560
Chapter 70
An empty digit sequence is considered to have one decoding. It may be assumed that the
input contains valid digits from 0 to 9 and there are no leading 0’s, no extra trailing 0’s and
no two or more consecutive 0’s.
This problem is recursive and can be broken in sub-problems. We start from end of the
given digit sequence. We initialize the total count of decodings as 0. We recur for two
subproblems.
1) If the last digit is non-zero, recur for remaining (n-1) digits and add the result to total
count.
2) If the last two digits form a valid character (or smaller than 27), recur for remaining (n-2)
digits and add the result to total count.
Following is the implementation of the above approach.
CPP
561
Chapter 70. Count Possible Decodings of a given Digit Sequence
Java
562
Chapter 70. Count Possible Decodings of a given Digit Sequence
Python3
563
Chapter 70. Count Possible Decodings of a given Digit Sequence
count[0] = 1
count[1] = 1
for i in range(2, n+1):
count[i] = 0
# If the last digit is not 0,
# then last digit must add to
# the number of words
if (digits[i-1] > '0'):
count[i] = count[i-1]
# If second last digit is smaller
# than 2 and last digit is
# smaller than 7, then last two
# digits form a valid character
if (digits[i-2] == '1' or (digits[i-2] == '2' and digits[i-1] < '7') ):
count[i] += count[i-2]
return count[n]
# Driver program to test above function
digits = ['1','2','3','4']
n = len(digits)
print("Count is ",countDecodingDP(digits, n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
564
Chapter 70. Count Possible Decodings of a given Digit Sequence
]
Output:
Count is 3
The time complexity of above the code is exponential. If we take a closer look at the above
program, we can observe that the recursive solution is similar to Fibonacci Numbers. There-
fore, we can optimize the above solution to work in O(n) time using Dynamic Programming.
Following is C++ implementation for the same.
565
Chapter 70. Count Possible Decodings of a given Digit Sequence
#include <iostream>
#include <cstring>
using namespace std;
// A Dynamic Programming based function to count decodings
int countDecodingDP(char *digits, int n)
{
int count[n+1]; // A table to store results of subproblems
count[0] = 1;
count[1] = 1;
for (int i = 2; i <= n; i++)
{
count[i] = 0;
// If the last digit is not 0, then last digit must add to
// the number of words
if (digits[i-1] > '0')
count[i] = count[i-1];
// If second last digit is smaller than 2 and last digit is
// smaller than 7, then last two digits form a valid character
if (digits[i-2] == '1' || (digits[i-2] == '2' && digits[i-1] < '7') )
count[i] += count[i-2];
}
return count[n];
}
// Driver program to test above function
int main()
{
char digits[] = "1234";
int n = strlen(digits);
cout << "Count is " << countDecodingDP(digits, n);
return 0;
}
Output:
Count is 3
Time Complexity of the above solution is O(n) and it requires O(n) auxiliary space. We can
reduce auxiliary space to O(1) by using space optimized version discussed in the Fibonacci
Number Post.
Improved By : nitin mittal
566
Chapter 70. Count Possible Decodings of a given Digit Sequence
Source
https://www.geeksforgeeks.org/count-possible-decodings-given-digit-sequence/
567
Chapter 71
568
Chapter 71. Count all increasing subsequences
ending at every index. Finally, we return sum of all values (In LCS problem, we return max
of all values).
Illustration:
569
Chapter 71. Count all increasing subsequences
Method 2 (Efficient)
The above solution doesn’t use the fact that we have only 10 possible values in given array.
We can use this fact by using an array count[] such that count[d] stores current count digits
smaller than d.
C++
570
Chapter 71. Count all increasing subsequences
Java
571
Chapter 71. Count all increasing subsequences
572
Chapter 71. Count all increasing subsequences
}
}
// This code is contributed by Prerna Saini
Python3
# Python3 program to count increasing
# subsequences in an array of digits.
# Function To Count all the sub-
# sequences possible in which digit
# is greater than all previous digits
# arr[] is array of n digits
def countSub(arr, n):
# count[] array is used to store all
# sub-sequences possible using that
# digit count[] array covers all the
# digit from 0 to 9
count = [0 for i in range(10)]
# scan each digit in arr[]
for i in range(n):
# count all possible sub-sequences by
# the digits less than arr[i] digit
for j in range(arr[i] - 1, -1, -1):
count[arr[i]] += count[j]
# store sum of all sub-sequences
# plus 1 in count[] array
count[arr[i]] += 1
# Now sum up the all sequences
# possible in count[] array
result = 0
for i in range(10):
result += count[i]
return result
# Driver Code
arr = [3, 2, 4, 5, 4]
n = len(arr)
print(countSub(arr, n))
573
Chapter 71. Count all increasing subsequences
C#
574
Chapter 71. Count all increasing subsequences
int n = arr.Length;
Console.WriteLine(countSub(arr,n));
}
}
// This code is contributed by Anant Agarwal.
Output:
14
Time Complexity : O(n) Note that the inner loop runs at most 10 times.
Auxiliary Space : O(1) Note that count has at-most 10 elements.
Source
https://www.geeksforgeeks.org/count-all-increasing-subsequences/
575
Chapter 72
Count all possible paths from top left to bottom right of a mXn matrix - GeeksforGeeks
The problem is to count all the possible paths from top left to bottom right of a mXn matrix
with the constraints that from each cell you can either move only to right or down
Examples :
Input : m = 2, n = 2;
Output : 2
There are two paths
(0, 0) -> (0, 1) -> (1, 1)
(0, 0) -> (1, 0) -> (1, 1)
Input : m = 2, n = 3;
Output : 3
There are three paths
(0, 0) -> (0, 1) -> (0, 2) -> (1, 2)
(0, 0) -> (0, 1) -> (1, 1) -> (1, 2)
(0, 0) -> (1, 0) -> (1, 1) -> (1, 2)
We have discussed a solution to print all possible paths, counting all paths is easier. Let
NumberOfPaths(m, n) be the count of paths to reach row number m and column number n
in the matrix, NumberOfPaths(m, n) can be recursively written as following.
C++
#include <iostream>
576
Chapter 72. Count all possible paths from top left to bottom right of a mXn matrix
Java
577
Chapter 72. Count all possible paths from top left to bottom right of a mXn matrix
Python
Output:
The time complexity of above recursive solution is exponential. There are many overlap-
ping subproblems. We can draw a recursion tree for numberOfPaths(3, 3) and see many
overlapping subproblems. The recursion tree would be similar to Recursion tree for Longest
Common Subsequence problem.
So this problem has both properties (see this and this) of a dynamic programming problem.
578
Chapter 72. Count all possible paths from top left to bottom right of a mXn matrix
#include <iostream>
using namespace std;
// Returns count of possible paths to reach cell at
// row number m and column number n from the topmost
// leftmost cell (cell at 1, 1)
int numberOfPaths(int m, int n)
{
// Create a 2D table to store results of subproblems
int count[m][n];
// Count of paths to reach any cell in first column is 1
for (int i = 0; i < m; i++)
count[i][0] = 1;
// Count of paths to reach any cell in first column is 1
for (int j = 0; j < n; j++)
count[0][j] = 1;
// Calculate count of paths for other cells in
// bottom-up manner using the recursive solution
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; j++)
// By uncommenting the last part the code calculatest he total
// possible paths if the diagonal Movements are allowed
count[i][j] = count[i-1][j] + count[i][j-1]; //+ count[i-1][j-1];
}
return count[m-1][n-1];
}
// Driver program to test above functions
int main()
{
cout << numberOfPaths(3, 3);
return 0;
}
Java
579
Chapter 72. Count all possible paths from top left to bottom right of a mXn matrix
Python
580
Chapter 72. Count all possible paths from top left to bottom right of a mXn matrix
Output:
581
Chapter 72. Count all possible paths from top left to bottom right of a mXn matrix
class GFG
{
// Returns count of possible paths to reach
// cell at row number m and column number n from
// the topmost leftmost cell (cell at 1, 1)
static int numberOfPaths(int m, int n)
{
// Create a 1D array to store results of subproblems
int[] dp = new int[n];
dp[0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[j] += dp[j - 1];
}
}
return dp[n - 1];
}
// Driver program to test above function
public static void main(String args[])
{
System.out.println(numberOfPaths(3, 3));
}
}
Output:
Source
https://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-right-nxm-matrix/
582
Chapter 73
Count all possible walks from a source to a destination with exactly k edges - GeeksforGeeks
Given a directed graph and two vertices ‘u’ and ‘v’ in it, count all possible walks from ‘u’
to ‘v’ with exactly k edges on the walk.
The graph is given as adjacency matrix representation where value of graph[i][j] as 1 indicates
that there is an edge from vertex i to vertex j and a value 0 indicates no edge from i to j.
For example consider the following graph. Let source ‘u’ be vertex 0, destination ‘v’ be 3
and k be 2. The output should be 2 as there are two walk from 0 to 3 with exactly 2 edges.
The walks are {0, 2, 3} and {0, 1, 3}
A simple solution is to start from u, go to all adjacent vertices and recur for adjacent
583
Chapter 73. Count all possible walks from a source to a destination with exactly k edges
vertices with k as k-1, source as adjacent vertex and destination as v. Following is the
implementation of this simple solution.
C++
Java
584
Chapter 73. Count all possible walks from a source to a destination with exactly k edges
import java.util.*;
import java.lang.*;
import java.io.*;
class KPaths
{
static final int V = 4; //Number of vertices
// A naive recursive function to count walks from u
// to v with k edges
int countwalks(int graph[][], int u, int v, int k)
{
// Base cases
if (k == 0 && u == v) return 1;
if (k == 1 && graph[u][v] == 1) return 1;
if (k <= 0) return 0;
// Initialize result
int count = 0;
// Go to all adjacents of u and recur
for (int i = 0; i < V; i++)
if (graph[u][i] == 1) // Check if is adjacent of u
count += countwalks(graph, i, v, k-1);
return count;
}
// Driver method
public static void main (String[] args) throws java.lang.Exception
{
/* Let us create the graph shown in above diagram*/
int graph[][] =new int[][] { {0, 1, 1, 1},
{0, 0, 0, 1},
{0, 0, 0, 1},
{0, 0, 0, 0}
};
int u = 0, v = 3, k = 2;
KPaths p = new KPaths();
System.out.println(p.countwalks(graph, u, v, k));
}
}//Contributed by Aakash Hasija
Python3
585
Chapter 73. Count all possible walks from a source to a destination with exactly k edges
C#
586
Chapter 73. Count all possible walks from a source to a destination with exactly k edges
587
Chapter 73. Count all possible walks from a source to a destination with exactly k edges
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to count walks from u
// to v with exactly k edges
// Number of vertices in the graph
$V = 4;
// A naive recursive function to count
// walks from u to v with k edges
function countwalks( $graph, $u, $v, $k)
{
global $V;
// Base cases
if ($k == 0 and $u == $v)
return 1;
if ($k == 1 and $graph[$u][$v])
return 1;
if ($k <= 0)
return 0;
// Initialize result
$count = 0;
// Go to all adjacents of u and recur
for ( $i = 0; $i < $V; $i++)
// Check if is adjacent of u
if ($graph[$u][$i] == 1)
$count += countwalks($graph, $i,
$v, $k - 1);
return $count;
}
// Driver Code
/* Let us create the graph
shown in above diagram*/
$graph = array(array(0, 1, 1, 1),
array(0, 0, 0, 1),
array(0, 0, 0, 1),
588
Chapter 73. Count all possible walks from a source to a destination with exactly k edges
array(0, 0, 0, 0));
$u = 0; $v = 3; $k = 2;
echo countwalks($graph, $u, $v, $k);
// This code is contributed by anuj_67.
?>
Output:
The worst case time complexity of the above function is O(Vk ) where V is the number of
vertices in the given graph. We can simply analyze the time complexity by drawing recursion
tree. The worst occurs for a complete graph. In worst case, every internal node of recursion
tree would have exactly n children.
We can optimize the above solution using Dynamic Programming. The idea is to build
a 3D table where first dimension is source, second dimension is destination, third dimension
is number of edges from source to destination, and the value is count of walks. Like other
Dynamic Programming problems, we fill the 3D table in bottom up manner.
C++
589
Chapter 73. Count all possible walks from a source to a destination with exactly k edges
if (e == 0 && i == j)
count[i][j][e] = 1;
if (e == 1 && graph[i][j])
count[i][j][e] = 1;
// go to adjacent only when number of edges is more than 1
if (e > 1)
{
for (int a = 0; a < V; a++) // adjacent of source i
if (graph[i][a])
count[i][j][e] += count[a][j][e-1];
}
}
}
}
return count[u][v][k];
}
// driver program to test above function
int main()
{
/* Let us create the graph shown in above diagram*/
int graph[V][V] = { {0, 1, 1, 1},
{0, 0, 0, 1},
{0, 0, 0, 1},
{0, 0, 0, 0}
};
int u = 0, v = 3, k = 2;
cout << countwalks(graph, u, v, k);
return 0;
}
Java
590
Chapter 73. Count all possible walks from a source to a destination with exactly k edges
591
Chapter 73. Count all possible walks from a source to a destination with exactly k edges
C#
592
Chapter 73. Count all possible walks from a source to a destination with exactly k edges
count[i,j,e] +=
count[a,j,e-1];
}
}
}
}
return count[u,v,k];
}
// Driver method
public static void Main ()
{
/* Let us create the graph shown in
above diagram*/
int [,]graph = { {0, 1, 1, 1},
{0, 0, 0, 1},
{0, 0, 0, 1},
{0, 0, 0, 0} };
int u = 0, v = 3, k = 2;
Console.WriteLine(
countwalks(graph, u, v, k));
}
}
// This is Code Contributed by anuj_67.
Output:
Time complexity of the above DP based solution is O(V3 K) which is much better than the
naive solution.
We can also use Divide and Conquer to solve the above problem in O(V3 Logk) time.
The count of walks of length k from u to v is the [u][v]’th entry in (graph[V][V])k . We
can calculate power of by doing O(Logk) multiplication by using the divide and conquer
technique to calculate power. A multiplication between two matrices of size V x V takes
O(V3 ) time. Therefore overall time complexity of this method is O(V3 Logk).
Improved By : nitin mittal, vt_m
Source
https://www.geeksforgeeks.org/count-possible-paths-source-destination-exactly-k-edges/
593
Chapter 74
Input : [1, 2, 3, 4]
k = 10
Output :11
The subsequences are {1}, {2}, {3}, {4},
{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4},
{1, 2, 3}, {1, 2, 4}
Input : [4, 8, 7, 2]
k = 50
Output : 9
This problem can be solved using dynamic programming where dp[i][j] = number of
subsequences having product less than i using first j terms of the array. Which can be
obtained by : number of subsequences using first j-1 terms + number of subsequences that
can be formed using j-th term.
C++
594
Chapter 74. Count all subsequences having product less than K
Java
595
Chapter 74. Count all subsequences having product less than K
Python
596
Chapter 74. Count all subsequences having product less than K
Output:
11
Improved By : pk_tautolo
Source
https://www.geeksforgeeks.org/count-subsequences-product-less-k/
597
Chapter 75
Input:
N = 5
2 5 1 20 6
Output:
3
Explanation:
There are only 3 triplets whose total sum is a perfect cube.
Indices Values SUM
0 1 2 2 5 1 8
0 1 3 2 5 20 27
2 3 4 1 20 6 27
Since 8 and 27 are prefect cube of 2 and 3.
Naive appraoch is to iterate over all the possible numbers by using 3 nested loops and
check whether their sum is perfect cube or not. The approach would be very slow as time
complexity can go up to O(n3 ).
An Efficient approach is to use dynamic programming and basic mathematics. According
to given condition sum of any of three positive integer is not greater than 15000. Therefore
there can be only 24(150001/3 ) cubes are possible in the range of 1 to 15000.
Now instead of iterating all triplets we can do much better by the help of above information.
Fixed first two indices i and j such that instead of iterating over all k(j < k � n), we can
598
Chapter 75. Count all triplets whose sum is equal to a perfect cube
iterate over all the 24 possible cubes, and for each one, (let’s say P) check how many
occurrence of P – (a[i] + a[j]) are in a[j+1, j+2, … n].
But if we compute the number of occurance of a number say K in a[j+1, j+2, … n] then
this would again be counted as slow approch and would definitely give TLE. So we have to
think a different approach.
Now here comes to a Dynamic Programming. Since all numbers are smaller than 5000 and
n is at most 1000. Hence we can compute a DP array as,
dp[i][K]:= Number of occurance of K in A[i, i+1, i+2 … n]
C++
599
Chapter 75. Count all triplets whose sum is equal to a perfect cube
int cube = k * k * k;
int rem = cube - (arr[i] + arr[j]);
// count all occurrence of third triplet
// in range from j+1 to n
if (rem > 0)
ans += dp[n - 1][rem] - dp[j][rem];
}
}
}
return ans;
}
// Driver code
int main()
{
int arr[] = { 2, 5, 1, 20, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << countTripletSum(arr, n);
return 0;
}
Java
600
Chapter 75. Count all triplets whose sum is equal to a perfect cube
// else add +1 to current state
// with previous state
else if(arr[i] == j)
dp[i][j] = dp[i - 1][j] + 1;
else
dp[i][j] = dp[i - 1][j];
}
}
}
// Function to calculate triplets whose sum
// is equal to the pefect cube
public static int countTripletSum(int arr[], int n)
{
computeDpArray(arr, n);
int ans = 0; // Initialize answer
for (int i = 0; i < n - 2; ++i) {
for (int j = i + 1; j < n - 1; ++j) {
for (int k = 1; k <= 24; ++k) {
int cube = k * k * k;
int rem = cube - (arr[i] + arr[j]);
// count all occurrence of
// third triplet in range
// from j+1 to n
if (rem > 0)
ans += dp[n - 1][rem] - dp[j][rem];
}
}
}
return ans;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = { 2, 5, 1, 20, 6 };
int n = arr.length;
dp = new int[1001][15001];
System.out.println(countTripletSum(arr, n));
}
}
601
Chapter 75. Count all triplets whose sum is equal to a perfect cube
Output:
Source
https://www.geeksforgeeks.org/count-triplets-whose-sum-equal-perfect-cube/
602
Chapter 76
Count binary strings with k times appearing adjacent two set bits - GeeksforGeeks
Given two integers n and k, count the number of binary strings of length n with k as number
of times adjacent 1’s appear.
Examples:
Input : n = 5, k = 2
Output : 6
Explanation:
Binary strings of length 5 in which k number of times
two adjacent set bits appear.
00111
01110
11100
11011
10111
11101
Input : n = 4, k = 1
Output : 3
Explanation:
Binary strings of length 3 in which k number of times
two adjacent set bits appear.
0011
1100
0110
603
Chapter 76. Count binary strings with k times appearing adjacent two set bits
Lets try writing the recursive function for the above problem statement:
1) n = 1, only two binary strings exist with length 1, not having any adjacent 1’s
String 1 : “0”
String 2 : “1”
2) For all n > 1 and all k, two cases arise
a) Strings ending with 0 : String of length n can be created by appending 0 to all
strings of length n-1 having k times two adjacent 1’s ending with both 0 and 1
(Having 0 at n’th position will not change the count of adjacent 1’s).
b) Strings ending with 1 : String of length n can be created by appending 1 to all strings
of length n-1 having k times adjacent 1’s and ending with 0 and to all strings of
length n-1 having k-1 adjacent 1’s and ending with 1.
Example: let s = 011 i.e. a string ending with 1 having adjacent count as 1. Adding 1 to it,
s = 0111 increase the count of adjacent 1.
604
Chapter 76. Count binary strings with k times appearing adjacent two set bits
for (int i=2; i<=n; i++)
{
// number of adjacent 1's can not exceed i-1
for (int j=0; j<i; j++)
{
dp[i][j][0] = dp[i-1][j][0] + dp[i-1][j][1];
dp[i][j][1] = dp[i-1][j][0];
if (j-1 >= 0)
dp[i][j][1] += dp[i-1][j-1][1];
}
}
return dp[n][k][0] + dp[n][k][1];
}
// Driver code
int main()
{
int n=5, k=2;
cout << countStrings(n, k);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/count-binary-strings-k-times-appearing-adjacent-two-set-bits/
605
Chapter 77
Examples :
Input : "1119"
Output: 7
Sub-groups: [1-119], [1-1-19], [1-11-9], [1-1-1-9],
[11-19] and [111-9].
Note : Here we have included [1119] in the group and
sum of digits is 12 and this group has no
immediate right.
Input : "1234"
Output: 6
Sub-groups : [1234], [1-234], [12-34], [1-2-3-4],
[12-3-4] and [1-2-34]
Let “length” be the length of input number. A recursive solution is to consider every position
from 0 length-1. For every position, recursively count all possible subgroups after it. Below
is C++ implementation of naive recursive solution.
606
Chapter 77. Count digit groupings of a number with given constraints
C++
607
Chapter 77. Count digit groupings of a number with given constraints
int main()
{
char num[] = "1119";
int len = strlen(num);
cout << countGroups(0, 0, len, num);
return 0;
}
Java
608
Chapter 77. Count digit groupings of a number with given constraints
// Note : We pass current
// sum as previous sum
res += countGroups(i + 1, sum,
length, num);
}
// Total number of subgroups
// till current position
return res;
}
// Driver Code
public static void main (String[] args)
{
String num = "1119";
int len =num .length();
System.out.println(countGroups(0, 0,
len, num));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to count number of
// ways to group digits of a number
// such that sum of digits in every
// subgroup is less than or equal
// to its immediate right subgroup.
// Function to find the subgroups
function countGroups($position,
$previous_sum,
$length,$num)
{
// Terminating Condition
if ($position == $length)
return 1;
$res = 0;
// sum of digits
$sum = 0;
// Traverse all digits from
609
Chapter 77. Count digit groupings of a number with given constraints
Output :
If we take a closer look at above recursive solution, we notice that there may be overlapping
subproblems. For example, if input number is 12345, then for position = 3 and previ-
ous_sum = 3, we recur two times. Similarly for position 4 and previous_sum = 7, we recur
two times. Therefore the above solution can be optimized using Dynamic Programming.
Below is a Dynamic Programming based solution for this problem.
1. The maximum sum of digits can be 9*length where ‘length’ is length of input num.
2. Create a 2D array int dp[MAX][9*MAX] where MAX is maximum possible length of
input numebr. A value dp[position][previous] is going to store result for ‘position’ and
‘previous_sum’.
3. If current subproblem has been evaluated i.e; dp[position][previous_sum] != -1, then
use this result, else recursively compute its value.
610
Chapter 77. Count digit groupings of a number with given constraints
4. If by including the current position digit in sum i.e; sum = sum + num[position]-‘0’,
sum becomes greater than equal to previous sum, then increment the result and call
the problem for next position in the num.
5. If position == length, then we have been traversed current subgroup successfully and
we return 1;
611
Chapter 77. Count digit groupings of a number with given constraints
int res = 0;
// sum of digits
int sum = 0;
// Traverse all digits from
// current position to rest
// of the length of string
for (int i = position; i < length; i++)
{
sum += (num[i] - '0');
// If forward_sum is greater
// than the previous sum,
// then call the method again
if (sum >= previous_sum)
// Note : We pass current
// sum as previous sum
res += countGroups(i + 1, sum,
length, num);
}
dp[position][previous_sum] = res;
// total number of subgroups
// till current position
return res;
}
// Driver Code
int main()
{
char num[] = "1119";
int len = strlen(num);
// Initialize dp table
memset(dp, -1, sizeof(dp));
cout << countGroups(0, 0, len, num);
return 0;
}
Output :
612
Chapter 77. Count digit groupings of a number with given constraints
Source
https://www.geeksforgeeks.org/count-groupings-number-sum-digits-every-sub-group-less-equals-immediate-right-su
613
Chapter 78
Input : S = geeksforgeeks, T = ge
Output : 6
T appears in S as below three subsequences.
[ge], [ ge], [g e], [g e] [g e]
and [ g e]
614
Chapter 78. Count distinct occurrences as a subsequence
Since there are overlapping subproblems in above recurrence result, we can apply dynamic
programming approach to solve above problem. We create a 2D array mat[m+1][n+1]
where m is length of string T and n is length of string S. mat[i][j] denotes the number of
distinct subsequence of substring S(1..i) and substring T(1..j) so mat[m][n] contains our
solution.
C++
615
Chapter 78. Count distinct occurrences as a subsequence
mat[0][j] = 1;
// Fill mat[][] in bottom up manner
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
// If last characters don't match, then value
// is same as the value without last character
// in S.
if (T[i - 1] != S[j - 1])
mat[i][j] = mat[i][j - 1];
// Else value is obtained considering two cases.
// a) All substrings without last character in S
// b) All substrings without last characters in
// both.
else
mat[i][j] = mat[i][j - 1] + mat[i - 1][j - 1];
}
}
/* uncomment this to print matrix mat
for (int i = 1; i <= m; i++, cout << endl)
for (int j = 1; j <= n; j++)
cout << mat[i][j] << " "; */
return mat[m][n];
}
// Driver code to check above method
int main()
{
string T = "ge";
string S = "geeksforgeeks";
cout << findSubsequenceCount(S, T) << endl;
return 0;
}
Java
616
Chapter 78. Count distinct occurrences as a subsequence
617
Chapter 78. Count distinct occurrences as a subsequence
String S = "geeksforgeeks";
System.out.println(findSubsequenceCount(S, T));
}
}
// This code is contributed by vt_m
C#
618
Chapter 78. Count distinct occurrences as a subsequence
// Else value is obtained considering two cases.
// a) All substrings without last character in S
// b) All substrings without last characters in
// both.
else
mat[i, j] = mat[i, j - 1] + mat[i - 1, j - 1];
}
}
/* uncomment this to print matrix mat
for (int i = 1; i <= m; i++, cout << endl)
for (int j = 1; j <= n; j++)
System.out.println ( mat[i][j] +" "); */
return mat[m, n];
}
// Driver code to check above method
public static void Main()
{
string T = "ge";
string S = "geeksforgeeks";
Console.WriteLine(findSubsequenceCount(S, T));
}
}
// This code is contributed by vt_m
Output:
Source
https://www.geeksforgeeks.org/count-distinct-occurrences-as-a-subsequence/
619
Chapter 79
Count even length binary sequences with same sum of first and second half bits - Geeks-
forGeeks
Given a number n, find count of all binary sequences of length 2n such that sum of first n
bits is same as sum of last n bits.
Examples:
Input: n = 1
Output: 2
There are 2 sequences of length 2*n, the
sequences are 00 and 11
Input: n = 2
Output: 2
There are 6 sequences of length 2*n, the
sequences are 0101, 0110, 1010, 1001, 0000
and 1111
The idea is to fix first and last bits and then recur for n-1, i.e., remaining 2(n-1) bits. There
are following possibilities when we fix first and last bits.
1) First and last bits are same, remaining n-1 bits on both sides should also have the same
sum.
2) First bit is 1 and last bit is 0, sum of remaining n-1 bits on left side should be 1 less
than the sum n-1 bits on right side.
2) First bit is 0 and last bit is 1, sum of remaining n-1 bits on left side should be 1 more
than the sum n-1 bits on right side.
620
Chapter 79. Count even length binary sequences with same sum of first and second half bits
C++
621
Chapter 79. Count even length binary sequences with same sum of first and second half bits
return 1;
int res = // First bit is 0 & last bit is 1
countSeq(n-1, diff+1) +
// First and last bits are same
2*countSeq(n-1, diff) +
// First bit is 1 & last bit is 0
countSeq(n-1, diff-1);
return res;
}
// Driver program
int main()
{
int n = 2;
cout << "Count of sequences is "
<< countSeq(2, 0);
return 0;
}
Java
622
Chapter 79. Count even length binary sequences with same sum of first and second half bits
Python3
623
Chapter 79. Count even length binary sequences with same sum of first and second half bits
C#
624
Chapter 79. Count even length binary sequences with same sum of first and second half bits
PHP
<?php
// A Naive Recursive PHP program
// to count even length binary
// sequences such that the sum of
// first and second half bits is same
// diff is difference between
// sums first n bits and last
// n bits respectively
function countSeq($n, $diff)
{
// We can't cover difference of
// more than n with 2n bits
if (abs($diff) > $n)
return 0;
// n == 1, i.e., 2
// bit long sequences
if ($n == 1 && $diff == 0)
return 2;
if ($n == 1 && abs($diff) == 1)
return 1;
$res = // First bit is 0 & last bit is 1
countSeq($n - 1, $diff + 1) +
// First and last bits are same
2 * countSeq($n - 1, $diff) +
625
Chapter 79. Count even length binary sequences with same sum of first and second half bits
Output:
Count of sequences is 6
The time complexity of above solution is exponential. If we draw the complete recursion
tree, we can observer that many subproblems are solved again and again. For example,
when we start from n = 4 and diff = 0, we can reach (3, 0) through multiple paths. Since
same suproblems are called again, this problem has Overlapping Subprolems property. So
min square sum problem has both properties (see thisand this) of a Dynamic Program-
ming problem.
Below is a memoization based solution that uses a lookup table to compute the result.
C++
626
Chapter 79. Count even length binary sequences with same sum of first and second half bits
return 0;
// n == 1, i.e., 2 bit long sequences
if (n == 1 && dif == 0)
return 2;
if (n == 1 && abs(dif) == 1)
return 1;
// Check if this subbproblem is already solved
// n is added to dif to make sure index becomes
// positive
if (lookup[n][n+dif] != -1)
return lookup[n][n+dif];
int res = // First bit is 0 & last bit is 1
countSeqUtil(n-1, dif+1) +
// First and last bits are same
2*countSeqUtil(n-1, dif) +
// First bit is 1 & last bit is 0
countSeqUtil(n-1, dif-1);
// Store result in lookup table and return the result
return lookup[n][n+dif] = res;
}
// A Wrapper over countSeqUtil(). It mainly initializes lookup
// table, then calls countSeqUtil()
int countSeq(int n)
{
// Initialize all entries of lookup table as not filled
memset(lookup, -1, sizeof(lookup));
// call countSeqUtil()
return countSeqUtil(n, 0);
}
// Driver program
int main()
{
int n = 2;
cout << "Count of sequences is "
<< countSeq(2);
return 0;
}
Java
627
Chapter 79. Count even length binary sequences with same sum of first and second half bits
628
Chapter 79. Count even length binary sequences with same sum of first and second half bits
Output:
Count of sequences is 6
Worst case time complexity of this solution is O(n2 ) as diff can be maximum n.
Below is O(n) solution for the same.
629
Chapter 79. Count even length binary sequences with same sum of first and second half bits
No. of 2*n bit strings such that first n bits have 0 ones &
last n bits have 0 ones = nC0 * nC0
No. of 2*n bit strings such that first n bits have 1 ones &
last n bits have 1 ones = nC1 * nC1
....
and so on.
C++
630
Chapter 79. Count even length binary sequences with same sum of first and second half bits
<< countSeq(n);
return 0;
}
Java
Python
631
Chapter 79. Count even length binary sequences with same sum of first and second half bits
PHP
<?php
// A Php program to count even
// length binary sequences
// such that the sum of first
// and second half bits is same
// Returns the count of
// even length sequences
function countSeq($n)
{
$nCr = 1;
$res = 1;
// Calculate SUM ((nCr)^2)
for ($r = 1; $r <= $n; $r++)
632
Chapter 79. Count even length binary sequences with same sum of first and second half bits
{
// Compute nCr using nC(r-1)
// nCr/nC(r-1) = (n+1-r)/r;
$nCr = ($nCr * ($n + 1 - $r)) / $r;
$res = $res + ($nCr * $nCr);
}
return $res;
}
// Driver Code
$n = 2;
echo ("Count of sequences is ");
echo countSeq($n);
// This code is contributed
// by Shivi_Aggarwal
?>
Output:
Count of sequences is 6
Thanks to d_geeks, Saurabh Jain and Mysterious Mind for suggesting above O(n) solution.
This article is contributed by Pawan. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : nitin mittal, shiv_bhakt, Shivi_Aggarwal
Source
https://www.geeksforgeeks.org/count-even-length-binary-sequences-with-same-sum-of-first-and-second-half-bits/
633
Chapter 80
Input: N = 2
Output: 3
// The 3 strings are 00, 01, 10
Input: N = 3
Output: 5
// The 5 strings are 000, 001, 010, 100, 101
This problem can be solved using Dynamic Programming. Let a[i] be the number of binary
strings of length i which do not contain any two consecutive 1’s and which end in 0. Similarly,
let b[i] be the number of such strings which end in 1. We can append either 0 or 1 to a string
ending in 0, but we can only append 0 to a string ending in 1. This yields the recurrence
relation:
The base cases of above recurrence are a[1] = b[1] = 1. The total number of strings of length
i is just a[i] + b[i].
634
Chapter 80. Count number of binary strings without consecutive 1’s
Java
class Subset_sum
{
static int countStrings(int n)
{
int a[] = new int [n];
int b[] = new int [n];
a[0] = b[0] = 1;
for (int i = 1; i < n; i++)
{
a[i] = a[i-1] + b[i-1];
b[i] = a[i-1];
}
return a[n-1] + b[n-1];
}
/* Driver program to test above function */
635
Chapter 80. Count number of binary strings without consecutive 1’s
Python3
C#
636
Chapter 80. Count number of binary strings without consecutive 1’s
b[i] = a[i-1];
}
return a[n-1] + b[n-1];
}
// Driver Code
public static void Main ()
{
Console.Write(countStrings(3));
}
}
// This code is contributed by nitin mittal
PHP
<?php
// PHP program to count all distinct
// binary stringswithout two
// consecutive 1's
function countStrings($n)
{
$a[$n] = 0;
$b[$n] = 0;
$a[0] = $b[0] = 1;
for ($i = 1; $i < $n; $i++)
{
$a[$i] = $a[$i - 1] +
$b[$i - 1];
$b[$i] = $a[$i - 1];
}
return $a[$n - 1] +
$b[$n - 1];
}
// Driver Code
echo countStrings(3) ;
// This code is contributed by nitin mittal
?>
Output:
637
Chapter 80. Count number of binary strings without consecutive 1’s
Source:
courses.csail.mit.edu/6.006/oldquizzes/solutions/q2-f2009-sol.pdf
If we take a closer look at the pattern, we can observe that the count is actually (n+2)’th
Fibonacci number for n >= 1. The Fibonacci Numbersare 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
89, 141, ….
n = 1, count = 2 = fib(3)
n = 2, count = 3 = fib(4)
n = 3, count = 5 = fib(5)
n = 4, count = 8 = fib(6)
n = 5, count = 13 = fib(7)
................
Therefore we can count the strings in O(Log n) time also using the method 5 here.
Related Post :
1 to n bit numbers with no consecutive 1s in binary representation.
This article is contributed by Rahul Jain. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal, jit_t
Source
https://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive-1s/
638
Chapter 81
Input : arr[] = {12, 8, 11, 13, 10, 15, 14, 16, 20},
k = 4
Output : 39
Approach: The idea is to use Dynamic Programming by define 2D matrix, say dp[][].
dp[i][j] stores the count of increasing subsequences of size i ending with element arr[j]. So
dp[i][j] can be defined as:
C++
639
Chapter 81. Count number of increasing subsequences of size k
640
Chapter 81. Count number of increasing subsequences of size k
int main()
{
int arr[] = { 12, 8, 11, 13, 10, 15, 14, 16, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 4;
cout << "Number of Increasing Subsequences of size "
<< k << " = " << numOfIncSubseqOfSizeK(arr, n, k);
return 0;
}
PHP
<?php
// PHP implementation to count
// number of increasing
// subsequences of size k
// function to count number
// of increasing subsequences
// of size k
function numOfIncSubseqOfSizeK($arr,
$n, $k)
{
$dp = array(array());
$sum = 0;
$dp = array_fill(0, $n + 1, false);
// count of increasing
// subsequences of size 1
// ending at each arr[i]
for ($i = 0; $i < $n; $i++)
$dp[0][$i] = 1;
// building up the matrix
// dp[][]. Here 'l' signifies
// the size of increassing
// subsequnce of size (l+1).
for ($l = 1; $l < $k; $l++)
{
// for each increasing
// subsequence of size 'l'
// ending with element arr[i]
for ($i = $l; $i < $n; $i++)
{
641
Chapter 81. Count number of increasing subsequences of size k
Output:
642
Chapter 81. Count number of increasing subsequences of size k
Source
https://www.geeksforgeeks.org/count-number-increasing-subsequences-size-k/
643
Chapter 82
Examples:
Input: m = 3, n = 3, k = 2
Output: 4
See below diagram for four paths with
maximum 2 turns.
Input: m = 3, n = 3, k = 1
Output: 2
644
Chapter 82. Count number of paths with at-most k turns
We strongly recommend you to minimize your browser and try this yourself
first.
This problem can be recursively computed using below recursive formula.
// Base cases
645
Chapter 82. Count number of paths with at-most k turns
We can solve this problem in Polynomial Time using Dynamic Programming. The idea is to
use a 4 dimensional table dp[m][n][k][d] where m is number of rows, n is number of columns,
k is number of allowed turns and d is direction.
Below is Dynamic Programming based C++ implementation.
646
Chapter 82. Count number of paths with at-most k turns
Output:
Number of paths is 4
Source
https://www.geeksforgeeks.org/count-number-of-paths-with-k-turns/
647
Chapter 83
Brute Force approach O(2n ): One naive approach is to generate all the 2n subsets and
count all the subsets having XOR value K, but this approach will not be efficient for large
values of n.
Dynamic Programming Approach O(n*m):
We define a number m such that m = pow(2,(log2(max(arr))+1)) – 1. This number is
actually the maximum value any XOR subset will acquire. We get this number by counting
bits in largest number. We create a 2D array dp[n+1][m+1], such that dp[i][j] equals to
the number of subsets having XOR value j from subsets of arr[0…i-1].
We fill the dp array as following:
648
Chapter 83. Count number of subsets having a particular XOR value
3. Iterate over all the values of arr[i] from left to right and for each arr[i], iterate over
all the possible values of XOR i.e from 0 to m (both inclusive) and fill the dp array
asfollowing:
for i = 1 to n:
for j = 0 to m:
dp[i][j] = dp[i-1][j] + dp[i-1][j^arr[i-1]]
This can be explained as, if there is a subset arr[0…i-2] with XOR value j, then there
also exists a subset arr[0…i-1] with XOR value j. also if there exists a subset arr[0….i-2]
with XOR value j^arr[i] then clearly there exist a subset arr[0…i-1] with XOR value j,
as j ^ arr[i-1] ^ arr[i-1] = j.
4. Counting the number of subsets with XOR value k: Since dp[i][j] is the number of
subsets having j as XOR value from the subsets of arr[0..i-1], then the number of
subsets from set arr[0..n] having XOR value as K will be dp[n][K]
C/C++
649
Chapter 83. Count number of subsets having a particular XOR value
PHP
<?php
// PHP arr dynamic programming
// solution to finding the number
// of subsets having xor of their
// elements as k
// Returns count of subsets of
// arr[] with XOR value equals to k.
function subsetXOR($arr, $n, $k)
{
// Find maximum element in arr[]
$max_ele = $arr[0];
for ($i = 1; $i < $n; $i++)
if ($arr[$i] > $max_ele)
$max_ele = $arr[$i];
// Maximum possible XOR value
$m = (1 << (int)(log($max_ele,
2) + 1) ) - 1;
// The value of dp[i][j] is the
// number of subsets having
// XOR of their elements as j
// from the set arr[0...i-1]
// Initializing all the
// values of dp[i][j] as 0
for ($i = 0; $i <= $n; $i++)
650
Chapter 83. Count number of subsets having a particular XOR value
Output :
Count of subsets is 4
This article is contributed by Pranay Pandey. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : jit_t
Source
https://www.geeksforgeeks.org/count-number-of-subsets-having-a-particular-xor-value/
651
Chapter 84
Examples :
Input: n = 3
Output: 4
Below are the four ways
1 step + 1 step + 1 step
1 step + 2 step
2 step + 1 step
3 step
Input: n = 4
Output: 7
C++
652
Chapter 84. Count number of ways to cover a distance
Java
653
Chapter 84. Count number of ways to cover a distance
Python3
C#
654
Chapter 84. Count number of ways to cover a distance
PHP
<?php
// A naive recursive PHP program to
// count number of ways to cover
// a distance with 1, 2 and 3 steps
// Returns count of ways to cover 'dist'
function printCountRec( $dist)
{
// Base cases
if ($dist<0) return 0;
if ($dist==0) return 1;
// Recur for all previous 3
// and add the results
return printCountRec($dist - 1) +
printCountRec($dist - 2) +
printCountRec($dist - 3);
}
// Driver Code
$dist = 4;
echo printCountRec($dist);
// This code is contributed by anuj_67.
?>
655
Chapter 84. Count number of ways to cover a distance
Output:
The time complexity of above solution is exponential, a close upper bound is O(3n ). If we
draw the complete recursion tree, we can observer that many subproblems are solved again
and again. For example, when we start from n = 6, we can reach 4 by subtracting one 2
times and by subtracting 2 one times. So the subproblem for 4 is called twice.
Since same suproblems are called again, this problem has Overlapping Subprolems property.
So min square sum problem has both properties (see thisand this) of a dynamic programming
problem. Like other typical Dynamic Programming(DP) problems, recomputations of same
subproblems can be avoided by constructing a temporary array count[] in bottom up manner.
Below is the implementation of above idea :
C++
Java
656
Chapter 84. Count number of ways to cover a distance
Python3
657
Chapter 84. Count number of ways to cover a distance
count[1] = 1
count[2] = 2
# Fill the count array in bottom
# up manner
for i in range(3, dist + 1):
count[i] = (count[i-1] +
count[i-2] + count[i-3])
return count[dist];
# driver program
dist = 4;
print( printCountDP(dist))
# This code is contributed by Sam007.
C#
658
Chapter 84. Count number of ways to cover a distance
// Driver Code
public static void Main ()
{
int dist = 4;
Console.WriteLine(printCountDP(dist));
}
}
// This code is contributed by Sam007.
PHP
<?php
// A Dynamic Programming based PHP program
// to count number of ways to cover a
// distance with 1, 2 and 3 steps
function printCountDP( $dist)
{
$count = array();
// Initialize base values. There is
// one way to cover 0 and 1 distances
// and two ways to cover 2 distance
$count[0] = 1; $count[1] = 1;
$count[2] = 2;
// Fill the count array
// in bottom up manner
for ( $i = 3; $i <= $dist; $i++)
$count[$i] = $count[$i - 1] +
$count[$i - 2] +
$count[$i - 3];
return $count[$dist];
}
// Driver Code
$dist = 4;
echo printCountDP($dist);
// This code is contributed by anuj_67.
?>
Output :
659
Chapter 84. Count number of ways to cover a distance
This article is contributed by Vignesh Venkatesan. Please write comments if you find any-
thing incorrect, or you want to share more information about the topic discussed above
Improved By : Sam007, vt_m
Source
https://www.geeksforgeeks.org/count-number-of-ways-to-cover-a-distance/
660
Chapter 85
Input : n = 1
Output : 1
Input : n = 2
Output : 1
We can only place both tiles horizontally
Input : n = 3
Output : 1
We can only place all tiles horizontally.
Input : n = 4
Output : 2
The two ways are :
1) Place all tiles horizontally
2) Place all tiles vertically.
Input : n = 5
Output : 3
We can fill a 5 x 4 grid in following ways :
1) Place all 5 tiles horizontally
2) Place first 4 vertically and 1 horizontally.
3) Place first 1 horizontally and 4 horizontally.
661
Chapter 85. Count number of ways to fill a “n x 4” grid using “1 x 4” tiles
1. Place the first tile horizontally : If we place first tile horizontally, the problem
reduces to “count(n-1)”
2. Place the first tile vertically : If we place first tile vertically, then we must place
3 more tiles vertically. So the problem reduces to “count(n-4)”
count(n) = 1 if n = 1 or n = 2 or n = 3
count(n) = 2 if n = 4
count(n) = count(n-1) + count(n-4)
This recurrence is similar to Fibonacci Numbers and can be solved using Dynamic program-
ming.
662
Chapter 85. Count number of ways to fill a “n x 4” grid using “1 x 4” tiles
C/C++
Java
663
Chapter 85. Count number of ways to fill a “n x 4” grid using “1 x 4” tiles
// on n x 4 grid
import java.io.*;
class Grid
{
// Function that count the number of ways to place 1 x 4 tiles
// on n x 4 grid.
static int count(int n)
{
// Create a table to store results of sub-problems
// dp[i] stores count of ways for i x 4 grid.
int[] dp = new int[n+1];
dp[0] = 0;
// Fill the table from d[1] to dp[n]
for(int i=1;i<=n;i++)
{
// Base cases
if (i >= 1 && i <= 3)
dp[i] = 1;
else if (i==4)
dp[i] = 2 ;
else
{
// dp(i-1) : Place first tile horizontally
// dp(i-4) : Place first tile vertically
// which means 3 more tiles have
// to be placed vertically.
dp[i] = dp[i-1] + dp[i-4];
}
}
return dp[n];
}
// Driver program
public static void main (String[] args)
{
int n = 5;
System.out.println("Count of ways is: " + count(n));
}
}
// Contributed by Pramod Kumar
Python
664
Chapter 85. Count number of ways to fill a “n x 4” grid using “1 x 4” tiles
# Returns count of count of ways to place 1 x 4 tiles
# on n x 4 grid.
def count(n):
# Create a table to store results of subproblems
# dp[i] stores count of ways for i x 4 grid.
dp = [0 for _ in range(n+1)]
# Fill the table from d[1] to dp[n]
for i in range(1,n+1):
# Base cases
if i <= 3:
dp[i] = 1
elif i == 4:
dp[i] = 2
else:
# dp(i-1) : Place first tile horizontally
# dp(n-4) : Place first tile vertically
# which means 3 more tiles have
# to be placed vertically.
dp[i] = dp[i-1] + dp[i-4]
return dp[n]
# Driver code to test above
n = 5
print ("Count of ways is"),
print (count(n))
C#
665
Chapter 85. Count number of ways to fill a “n x 4” grid using “1 x 4” tiles
PHP
<?php
// PHP program to count of ways to
// place 1 x 4 tiles on n x 4 grid.
666
Chapter 85. Count number of ways to fill a “n x 4” grid using “1 x 4” tiles
Output :
Count of ways is 3
667
Chapter 85. Count number of ways to fill a “n x 4” grid using “1 x 4” tiles
This article is contributed by Rajat Jha. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Sam007, nitin mittal
Source
https://www.geeksforgeeks.org/count-number-of-ways-to-fill-a-n-x-4-grid-using-1-x-4-tiles/
668
Chapter 86
Input : {3, 2, 0, 1}
Output : 2 1 -1 0
For 3 number of steps or jumps that
can be taken are 1, 2 or 3. The different ways are:
3 -> 2 -> 1
3 -> 1
669
Chapter 86. Count number of ways to jump to reach end
Input : {1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9}
Output : 52 52 28 16 8 -1 -1 4 2 1 0
This problem is a variation of Minimum number of jumps to reach end(Method 3). Here we
need to count all ways to reach end from every cell.
The solution is a modified version of the solution to the problem of Minimum number of
jumps to reach end(Method 3).
This problem aims to count the different ways to jump from each element so as to reach to
the end. For each element the count is being calculated by adding the counts of all those
forward elements that can reach to the end and to which the current element could reach +
1(if the element can directly reach to the end).
Algorithm:
countWays(arr, n)
Initialize array count_jump[n] = {0}
count_jump[n-1] = 0
for i = n-2 to 0
if arr[i] >= (n-i-1)
count_jump[i]++
for j=i+1; j < n-1 && j <= arr[i]+i; i++
if count_jump[j] != -1
count_jump[i] += count_jump[j]
if count_jump[i] == 0
count_jump[i] = -1
for i = 0 to n-1
print count_jump[i]
C++
670
Chapter 86. Count number of ways to jump to reach end
Java
671
Chapter 86. Count number of ways to jump to reach end
672
Chapter 86. Count number of ways to jump to reach end
countWaysToJump(arr, n);
}
}
// This code is contributed by Anant Agarwal.
Python3
673
Chapter 86. Count number of ways to jump to reach end
Output:
52 52 28 16 8 -1 -1 4 2 1 0
Source
https://www.geeksforgeeks.org/count-number-ways-jump-reach-end/
674
Chapter 87
Input: n = 3, k = 2
Output: 3
Explanation: Let the set be {1, 2, 3}, we can partition
it into 2 subsets in following ways
{{1,2}, {3}}, {{1}, {2,3}}, {{1,3}, {2}}
Input: n = 3, k = 1
Output: 1
Explanation: There is only one way {{1, 2, 3}}
We strongly recommend you to minimize your browser and try this yourself
first.
Let S(n, k) be total number of partitions of n elements into k sets. Value of S(n, k) can be
defined recursively as,
675
Chapter 87. Count number of ways to partition a set into k subsets
C++
Java
676
Chapter 87. Count number of ways to partition a set into k subsets
// k subsets
public static int countP(int n, int k)
{
// Base cases
if (n == 0 || k == 0 || k > n)
return 0;
if (k == 1 || k == n)
return 1;
// S(n+1, k) = k*S(n, k) + S(n, k-1)
return (k * countP(n - 1, k)
+ countP(n - 1, k - 1));
}
// Driver program
public static void main(String args[])
{
System.out.println(countP(3, 2));
}
}
//This code is contributed by Anshika Goyal.
C#
677
Chapter 87. Count number of ways to partition a set into k subsets
}
// Driver program
public static void Main()
{
Console.WriteLine(countP(3, 2));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// A PHP program to count
// number of partitions of
// a set with n elements
// into k subsets
// Returns count of different
// partitions of n elements
// in k subsets
function countP($n, $k)
{
// Base cases
if ($n == 0 || $k == 0 || $k > $n)
return 0;
if ($k == 1 || $k == $n)
return 1;
// S(n+1, k) = k*S(n, k)
// + S(n, k-1)
return $k * countP($n - 1, $k) +
countP($n - 1, $k - 1);
}
// Driver Code
echo countP(3, 2);
// This code is contributed by aj_36
?>
Output:
The time complexity of above recursive solution is exponential. The solution can be op-
timized as there are overlapping subproblems. For example, below is recursion tree of
countP(10,7). The subproblem countP(8,6) or CP(8,6) is called multiple times.
678
Chapter 87. Count number of ways to partition a set into k subsets
CP(10,7)
/ \
CP(9,7) CP(9,6)
/ \ / \
CP(8,7) CP(8,6) CP(8,6) CP(8,5)
/ \ / \ / \ / \
So this problem has both properties (see this and this) of a dynamic programming problem.
Like other typical Dynamic Programming(DP) problems, recomputations of same subprob-
lems can be avoided by constructing a temporary array dp[][] in bottom up manner using
the above recursive formula.
Below is C++ implementation of Dynamic Programming Solution.
679
Chapter 87. Count number of ways to partition a set into k subsets
return dp[n][k];
}
// Driver program
int main()
{
cout << countP(5, 2);
return 0;
}
Output:
15
Source
https://www.geeksforgeeks.org/count-number-of-ways-to-partition-a-set-into-k-subsets/
680
Chapter 88
Input: n = 20
Output: 4
There are following 4 ways to reach 20
(10, 10)
(5, 5, 10)
(5, 5, 5, 5)
(3, 3, 3, 3, 3, 5)
Input: n = 13
Output: 2
There are following 2 ways to reach 13
(3, 5, 5)
(3, 10)
This problem is a variation of coin change problem and can be solved in O(n) time and O(n)
auxiliary space.
The idea is to create a table of size n+1 to store counts of all scores from 0 to n. For every
possible move (3, 5 and 10), increment values in table.
C++
681
Chapter 88. Count number of ways to reach a given score in a game
682
Chapter 88. Count number of ways to reach a given score in a game
683
Chapter 88. Count number of ways to reach a given score in a game
return 0;
}
Java
684
Chapter 88. Count number of ways to reach a given score in a game
Python3
C#
685
Chapter 88. Count number of ways to reach a given score in a game
686
Chapter 88. Count number of ways to reach a given score in a game
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to count number of
// possible ways to a given score
// can be reached in a game where
// a move can earn 3 or 5 or 10
// Returns number of ways to reach
// score n
function counts($n)
{
// table[i] will store count
// of solutions for value i.
// Initialize all table
// values as 0
for($j = 0; $j < $n + 1; $j++)
$table[$j] = 0;
// Base case (If given value is 0)
$table[0] = 1;
// One by one consider given 3 moves
// and update the table[] values after
// the index greater than or equal to
// the value of the picked move
for ($i = 3; $i <= $n; $i++)
$table[$i] += $table[$i - 3];
for ($i = 5; $i <= $n; $i++)
$table[$i] += $table[$i - 5];
for ($i = 10; $i <= $n; $i++)
$table[$i] += $table[$i - 10];
return $table[$n];
}
// Driver Code
$n = 20;
echo "Count for ";
echo($n);
echo (" is ");
687
Chapter 88. Count number of ways to reach a given score in a game
echo counts($n);
$n = 13;
echo ("\n") ;
echo "Count for ";
echo($n);
echo (" is " );
echo counts($n);
// This code is contributed
// by Shivi_Aggarwal
?>
Output:
Count for 20 is 4
Count for 13 is 2
Exercise: How to count score when (10, 5, 5), (5, 5, 10) and (5, 10, 5) are considered
as different sequences of moves. Similarly, (5, 3, 3), (3, 5, 3) and (3, 3, 5) are considered
different.
This article is contributed by Rajeev Arora. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal, Shivi_Aggarwal
Source
https://www.geeksforgeeks.org/count-number-ways-reach-given-score-game/
688
Chapter 89
689
Chapter 89. Count number of ways to reach destination in a Maze
C++
690
Chapter 89. Count number of ways to reach destination in a Maze
}
// Similarly initialize the topmost row
for (int i=1; i<C; i++)
{
if (maze[0][i] == 0)
maze[0][i] = 1;
// If we encounter a blocked cell in bottommost
// row, there is no way of visiting any cell
// directly below it.
else
break;
}
// The only difference is that if a cell is -1,
// simply ignore it else recursively compute
// count value maze[i][j]
for (int i=1; i<R; i++)
{
for (int j=1; j<C; j++)
{
// If blockage is found, ignore this cell
if (maze[i][j] == -1)
continue;
// If we can reach maze[i][j] from maze[i-1][j]
// then increment count.
if (maze[i-1][j] > 0)
maze[i][j] = (maze[i][j] + maze[i-1][j]);
// If we can reach maze[i][j] from maze[i][j-1]
// then increment count.
if (maze[i][j-1] > 0)
maze[i][j] = (maze[i][j] + maze[i][j-1]);
}
}
// If the final cell is blocked, output 0, otherwise
// the answer
return (maze[R-1][C-1] > 0)? maze[R-1][C-1] : 0;
}
// Driver code
int main()
{
int maze[R][C] = {{0, 0, 0, 0},
{0, -1, 0, 0},
691
Chapter 89. Count number of ways to reach destination in a Maze
{-1, 0, 0, 0},
{0, 0, 0, 0}};
cout << countPaths(maze);
return 0;
}
Java
692
Chapter 89. Count number of ways to reach destination in a Maze
else
break;
}
// The only difference is that if a cell
// is -1, simply ignore it else recursively
// compute count value maze[i][j]
for (int i = 1; i < R; i++)
{
for (int j = 1; j <C ; j++)
{
// If blockage is found,
// ignore this cell
if (maze[i][j] == -1)
continue;
// If we can reach maze[i][j] from
// maze[i-1][j] then increment count.
if (maze[i - 1][j] > 0)
maze[i][j] = (maze[i][j] +
maze[i - 1][j]);
// If we can reach maze[i][j] from
// maze[i][j-1] then increment count.
if (maze[i][j - 1] > 0)
maze[i][j] = (maze[i][j] +
maze[i][j - 1]);
}
}
// If the final cell is blocked,
// output 0, otherwise the answer
return (maze[R - 1][C - 1] > 0) ?
maze[R - 1][C - 1] : 0;
}
// Driver code
public static void main (String[] args)
{
int maze[][] = {{0, 0, 0, 0},
{0, -1, 0, 0},
{-1, 0, 0, 0},
{0, 0, 0, 0}};
System.out.println (countPaths(maze));
}
693
Chapter 89. Count number of ways to reach destination in a Maze
}
// This code is contributed by vt_m
C#
694
Chapter 89. Count number of ways to reach destination in a Maze
break;
}
// The only difference is that if a cell
// is -1, simply ignore it else recursively
// compute count value maze[i][j]
for (int i = 1; i < R; i++)
{
for (int j = 1; j <C ; j++)
{
// If blockage is found,
// ignore this cell
if (maze[i,j] == -1)
continue;
// If we can reach maze[i][j] from
// maze[i-1][j] then increment count.
if (maze[i - 1,j] > 0)
maze[i,j] = (maze[i,j] +
maze[i - 1,j]);
// If we can reach maze[i][j] from
// maze[i][j-1] then increment count.
if (maze[i,j - 1] > 0)
maze[i,j] = (maze[i,j] +
maze[i,j - 1]);
}
}
// If the final cell is blocked,
// output 0, otherwise the answer
return (maze[R - 1,C - 1] > 0) ?
maze[R - 1,C - 1] : 0;
}
// Driver code
public static void Main ()
{
int [,]maze = { {0, 0, 0, 0},
{0, -1, 0, 0},
{-1, 0, 0, 0},
{0, 0, 0, 0}};
Console.Write (countPaths(maze));
}
}
695
Chapter 89. Count number of ways to reach destination in a Maze
PHP
<?php
// PHP program to count number
// of paths in a maze with obstacles.
$R = 4;
$C = 4;
// Returns count of possible
// paths in a maze[R][C]
// from (0,0) to (R-1,C-1)
function countPaths( $maze)
{
global $R, $C;
// If the initial cell is
// blocked, there is no
// way of moving anywhere
if ($maze[0][0] == - 1)
return 0;
// Initializing the
// leftmost column
for ( $i = 0; $i < $R; $i++)
{
if ($maze[$i][0] == 0)
$maze[$i][0] = 1;
// If we encounter a blocked
// cell in leftmost row,
// there is no way of
// visiting any cell
// directly below it.
else
break;
}
// Similarly initialize
// the topmost row
for($i = 1; $i < $C; $i++)
{
if ($maze[0][$i] == 0)
$maze[0][$i] = 1;
// If we encounter a blocked
696
Chapter 89. Count number of ways to reach destination in a Maze
697
Chapter 89. Count number of ways to reach destination in a Maze
Output:
Source
https://www.geeksforgeeks.org/count-number-ways-reach-destination-maze/
698
Chapter 90
Count of AP (Arithmetic
Progression) Subsequences in an
array
Input : arr[] = { 1, 2, 3 }
Output : 8
Arithmetic Progression subsequence from the
given array are: {}, { 1 }, { 2 }, { 3 }, { 1, 2 },
{ 2, 3 }, { 1, 3 }, { 1, 2, 3 }.
Input : arr[] = { 1, 2, 3, 4, 5 }
Output : 23
Since empty sequence and single element sequence is also arithmetic progression, so we
initialize the answer with n(number of element in the array) + 1.
Now, we need to find the arithmetic progression subsequence of length greater than or equal
to 2. Let minimum and maximum of the array be minarr and maxarr respectively. Observe,
in all the arithmetic progression subsequences, the range of common difference will be from
(minarr – maxarr) to (maxarr – minarr). Now, for each common difference, say d, calculate
the subsequence of length greater than or equal to 2 using dynamic programming.
Let dp[i] be the number of subsequence that end with arr[i] and have common difference of
699
Chapter 90. Count of AP (Arithmetic Progression) Subsequences in an array
d. So,
The number of subsequence of length greater than or equal to 2 with common difference d
is sum of dp[i] – 1, 0 <= i = 2 with difference d. To speed up, store the sum of dp[j] with
arr[j] + d = arr[i] and j < i. Below is implementation of above idea :
C++
700
Chapter 90. Count of AP (Arithmetic Progression) Subsequences in an array
Java
701
Chapter 90. Count of AP (Arithmetic Progression) Subsequences in an array
702
Chapter 90. Count of AP (Arithmetic Progression) Subsequences in an array
sum[a[i]] += dp[i];
}
}
return ans;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 2, 3 };
int n = arr.length;
System.out.println(numofAP(arr, n));
}
}
// This code is contributed by Anant Agarwal.
Python3
703
Chapter 90. Count of AP (Arithmetic Progression) Subsequences in an array
C#
704
Chapter 90. Count of AP (Arithmetic Progression) Subsequences in an array
// initializing the minimum value and
// maximum value of the array.
int minarr = +2147483647;
int maxarr = -2147483648;
int i;
// Finding the minimum and maximum
// value of the array.
for (i = 0; i < n; i++)
{
minarr = Math.Min(minarr, a[i]);
maxarr = Math.Max(maxarr, a[i]);
}
// dp[i] is going to store count of
// APs ending with arr[i].
// sum[j] is going to store sun of
// all dp[]'s with j as an AP element.
int []dp = new int[n];
int []sum = new int[MAX];
// Initialize answer with n + 1 as
// single elements and empty array
// are also DP.
int ans = n + 1;
// Traversing with all common
// difference.
for (int d = (minarr - maxarr);
d <= (maxarr - minarr); d++)
{
for(i = 0; i < MAX; i++)
sum[i]= 0;
// Traversing all the element
// of the array.
for ( i = 0; i < n; i++)
{
// Initialize dp[i] = 1.
dp[i] = 1;
// Adding counts of APs with
// given differences and a[i]
// is last element.
// We consider all APs where
705
Chapter 90. Count of AP (Arithmetic Progression) Subsequences in an array
Output :
Improved By : vt_m
Source
https://www.geeksforgeeks.org/count-arithmetic-progression-subsequences-array/
706
Chapter 91
707
Chapter 91. Count of Palindromic substrings in an Index range
Total time complexity of solution will be O(length ^ 2) for constructing dp array then O(1)
per query.
C/C++
708
Chapter 91. Count of Palindromic substrings in an Index range
Java
709
Chapter 91. Count of Palindromic substrings in an Index range
import java.io.*;
class GFG {
// Function to construct the dp array
static void constructDp(int dp[][], String str)
{
int l = str.length();
// declare 2D array isPalin, isPalin[i][j] will
// be 1 if str(i..j) is palindrome
int[][] isPalin = new int[l + 1][l + 1];
// initialize dp and isPalin array by zeros
for (int i = 0; i <= l; i++) {
for (int j = 0; j <= l; j++) {
isPalin[i][j] = dp[i][j] = 0;
}
}
// loop for starting index of range
for (int i = l - 1; i >= 0; i--) {
// initialize value for one character strings as 1
isPalin[i][i] = 1;
dp[i][i] = 1;
// loop for ending index of range
for (int j = i + 1; j < l; j++) {
/* isPalin[i][j] will be 1 if ith and
jth characters are equal and mid
substring str(i+1..j-1) is also a
palindrome */
isPalin[i][j] = (str.charAt(i) == str.charAt(j) && (i + 1 > j - 1 || (isPalin[i +
/* dp[i][j] will be addition of number
of palindromes from i to j-1 and i+1
to j subtracting palindromes from i+1
to j-1 (as counted twice) plus 1 if
str(i..j) is also a palindrome */
dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j];
}
}
}
// method returns count of palindromic substring in range (l, r)
static int countOfPalindromeInRange(int dp[][], int l, int r)
{
return dp[l][r];
}
710
Chapter 91. Count of Palindromic substrings in an Index range
// driver program
public static void main(String args[])
{
int MAX = 50;
String str = "xyaabax";
int[][] dp = new int[MAX][MAX];
constructDp(dp, str);
int l = 3;
int r = 5;
System.out.println(countOfPalindromeInRange(dp, l, r));
}
}
// Contributed by Pramod Kumar
C#
711
Chapter 91. Count of Palindromic substrings in an Index range
// loop for ending index of range
for (int j = i + 1; j < l; j++) {
/* isPalin[i][j] will be 1 if ith and
jth characters are equal and mid
substring str(i+1..j-1) is also a
palindrome*/
isPalin[i, j] = (str[i] == str[j] && (i + 1 > j - 1 ||
(isPalin[i + 1, j - 1]) != 0)) ? 1 : 0;
/* dp[i][j] will be addition of number
of palindromes from i to j-1 and i+1
to j subtracting palindromes from i+1
to j-1 (as counted twice) plus 1 if
str(i..j) is also a palindrome */
dp[i, j] = dp[i, j - 1] + dp[i + 1, j] -
dp[i + 1, j - 1] + isPalin[i, j];
}
}
}
// method returns count of palindromic
// substring in range (l, r)
static int countOfPalindromeInRange(int[, ] dp,
int l, int r)
{
return dp[l, r];
}
// driver program
public static void Main()
{
int MAX = 50;
string str = "xyaabax";
int[, ] dp = new int[MAX, MAX];
constructDp(dp, str);
int l = 3;
int r = 5;
Console.WriteLine(countOfPalindromeInRange(dp, l, r));
}
}
// This code is contributed by vt_m.
Output:
712
Chapter 91. Count of Palindromic substrings in an Index range
Improved By : vt_m
Source
https://www.geeksforgeeks.org/count-of-palindromic-substrings-in-an-index-range/
713
Chapter 92
Input : n = 4, k = 3, x = 2
Output : 3
The idea is to use Dynamic Programming and combinatorics to solve the problem.
First of all, notice that the answer is same for all x from 2 to k. It can easily be proved.
This will be useful later on.
Let the state f(i) denote the number of ways to fill the range [1, i] of array A such that A1
= 1 and Ai � 1.
Therefore, if x � 1, the answer to the problem is f(n)/(k – 1), because f(n) is the number
of way where An is filled with a number from 2 to k, and the answer are equal for all such
values An , so the answer for an individual value is f(n)/(k – 1).
Otherwise, if x = 1, the answer is f(n – 1), because An – 1 � 1, and the only number we can
fill An with is x = 1.
Now, the main problem is how to calculate f(i). Consider all numbers that Ai – 1 can be.
We know that it must lie in [1, k].
714
Chapter 92. Count of arrays having consecutive element with different values
• If Ai – 1 � 1, then there are (k – 2)f(i – 1) ways to fill in the rest of the array, because
Ai cannot be 1 or Ai – 1 (so we multiply with (k – 2)), and for the range [1, i – 1],
there are, recursively, f(i – 1) ways.
• If Ai – 1 = 1, then there are (k – 1)f(i – 2) ways to fill in the rest of the array, because
Ai – 1 = 1 means Ai – 2 � 1 which means there are f(i – 2)ways to fill in the range [1, i
– 2] and the only value that Ai cannot be 1, so we have (k – 1) choices for Ai .
C++
Java
715
Chapter 92. Count of arrays having consecutive element with different values
Python3
716
Chapter 92. Count of arrays having consecutive element with different values
dp.append(1)
# Computing f(i) for each 2 <= i <= n.
i = 2
while i < n:
dp.append( (k - 2) * dp[i - 1] +
(k - 1) * dp[i - 2])
i = i + 1
return ( (k - 1) * dp[n - 2] if x == 1 else dp[n - 1])
# Driven code
n = 4
k = 3
x = 2
print(countarray(n, k, x))
# This code is contributed by "Sharad_Bhardwaj".
C#
717
Chapter 92. Count of arrays having consecutive element with different values
{
int n = 4, k = 3, x = 2;
Console.WriteLine(countarray(n, k, x));
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP Program to find
// count of arrays.
$MAXN = 109;
// Return the number of arrays
// with given constartints.
function countarray($n, $k, $x)
{
$dp = array( 0 );
// Initalising dp[0] and dp[1].
$dp[0] = 0;
$dp[1] = 1;
// Computing f(i) for
// each 2 <= i <= n.
for ( $i = 2; $i < $n; $i++)
$dp[$i] = ($k - 2) * $dp[$i - 1] +
($k - 1) * $dp[$i - 2];
return ($x == 1 ? ($k - 1) *
$dp[$n - 2] : $dp[$n - 1]);
}
// Driven Code
$n = 4; $k = 3; $x = 2;
echo countarray($n, $k, $x) ;
// This code is contributed by anuj_67.
?>
Output :
Improved By : vt_m
718
Chapter 92. Count of arrays having consecutive element with different values
Source
https://www.geeksforgeeks.org/count-arrays-consecutive-element-different-values/
719
Chapter 93
Count of arrays in which all adjacent elements are such that one of them divide the another
- GeeksforGeeks
Given two positive integer n and n. The task is to find the number of arrays of size n that
can be formed such that :
Examples:
Input : n = 3, m = 3.
Output : 17
{1,1,1}, {1,1,2}, {1,1,3}, {1,2,1},
{1,2,2}, {1,3,1}, {1,3,3}, {2,1,1},
{2,1,2}, {2,1,3}, {2,2,1}, {2,2,2},
{3,1,1}, {3,1,2}, {3,1,3}, {3,3,1},
{3,3,3} are possible arrays.
Input : n = 1, m = 10.
Output : 10
We try to find number of possible values at each index of the array. First, at index 0 all
values are possible from 1 to m. Now observe for each index, we can reach either to its
720
Chapter 93. Count of arrays in which all adjacent elements are such that one of them
divide the another
multiple or its factor. So, precompute that and store it for all the elements. Hence for each
position i, ending with integer x, we can go to next position i + 1, with the array ending in
integer with multiple of x or factor of x. Also, multiple of x or factor of x must be less than
m.
So, we define an 2D array dp[i][j], which is number of possible array (divisible adjacent
element) of size i with j as its first index element.
721
Chapter 93. Count of arrays in which all adjacent elements are such that one of them
divide the another
}
di[i].push_back(i);
}
// Initalising for size 1 array for
// each i <= m.
for (int i = 1; i <= m; i++)
dp[1][i] = 1;
// Calculating the number of array possible
// of size i and starting with j.
for (int i = 2; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
dp[i][j] = 0;
// For all previous possible values.
// Adding number of factors.
for (auto x:di[j])
dp[i][j] += dp[i-1][x];
// Adding number of multiple.
for (auto x:mu[j])
dp[i][j] += dp[i-1][x];
}
}
// Calculating the total count of array
// which start from [1...m].
int ans = 0;
for (int i = 1; i <= m; i++)
{
ans += dp[n][i];
di[i].clear();
mu[i].clear();
}
return ans;
}
// Driven Program
int main()
{
int n = 3, m = 3;
cout << numofArray(n, m) << "\n";
return 0;
}
722
Chapter 93. Count of arrays in which all adjacent elements are such that one of them
divide the another
Output:
17
Source
https://www.geeksforgeeks.org/count-arrays-adjacent-elements-one-divide-another/
723
Chapter 94
Input : N = 4
Output : 4
Explanation: 1+1+1+1
1+3
3+1
4
Input : N = 5
Output : 6
Explanation: 1 + 1 + 1 + 1 + 1
1 + 4
4 + 1
1 + 1 + 3
1 + 3 + 1
3 + 1 + 1
Approach : Divide the problem into sub-problems for solving it. Let DP[n] be the be the
number of ways to write N as the sum of 1, 3, and 4. Consider one possible solution with n
= x1 + x2 + x3 + … xn. If the last number is 1, then sum of the remaining numbers is n-1.
So the number that ends with 1 is equal to DP[n-1]. Taking other cases into account where
the last number is 3 and 4. The final recurrence would be:
724
Chapter 94. Count of different ways to express N as the sum of 1, 3 and 4
Base case :
DP[0] = DP[1] = DP[2] = 1 and DP[3] = 2
C++
Java
725
Chapter 94. Count of different ways to express N as the sum of 1, 3 and 4
Python3
726
Chapter 94. Count of different ways to express N as the sum of 1, 3 and 4
return DP[n]
# Driver code
n = 10
print (countWays(n))
# This code is contributed by Gitanjali.
C#
// C# program to illustrate
// the number of ways to represent
// N as sum of 1, 3 and 4.
using System;
class GFG {
// Function to count the
// number of ways to represent
// n as sum of 1, 3 and 4
static int countWays(int n)
{
int []DP = new int[n + 1];
// base cases
DP[0] = DP[1] = DP[2] = 1;
DP[3] = 2;
// iterate for all values from 4 to n
for (int i = 4; i <= n; i++)
DP[i] = DP[i - 1] + DP[i - 3]
+ DP[i - 4];
return DP[n];
}
// Driver code
public static void Main()
{
int n = 10;
Console.WriteLine(countWays(n));
}
}
// This code is contributed
// by vt_m.
727
Chapter 94. Count of different ways to express N as the sum of 1, 3 and 4
PHP
<?php
// PHP program to illustrate
// the number of ways to
// represent N as sum of
// 1, 3 and 4.
// function to count the
// number of ways to
// represent n as sum of
// 1, 3 and 4
function countWays($n)
{
$DP = array();
// base cases
$DP[0] = $DP[1] = $DP[2] = 1;
$DP[3] = 2;
// iterate for all
// values from 4 to n
for ($i = 4; $i <= $n; $i++)
$DP[$i] = $DP[$i - 1] +
$DP[$i - 3] +
$DP[$i - 4];
return $DP[$n];
}
// Driver Code
$n = 10;
echo countWays($n);
// This code is contributed
// by Sam007
?>
Output:
64
728
Chapter 94. Count of different ways to express N as the sum of 1, 3 and 4
Source
https://www.geeksforgeeks.org/count-ofdifferent-ways-express-n-sum-1-3-4/
729
Chapter 95
Count of n digit numbers whose sum of digits equals to given sum - GeeksforGeeks
Given two integers ‘n’ and ‘sum’, find count of all n digit numbers with sum of digits as
‘sum’. Leading 0’s are not counted as digits.
1 <= n <= 100 and
1 <= sum <= 500
Example:
Input: n = 2, sum = 2
Output: 2
Explanation: Numbers are 11 and 20
Input: n = 2, sum = 5
Output: 5
Explanation: Numbers are 14, 23, 32, 41 and 50
Input: n = 3, sum = 6
Output: 21
The idea is simple, we subtract all values from 0 to 9 from given sum and recur for sum
minus that digit. Below is recursive formula.
730
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
C++
731
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
Java
732
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
}
// This is mainly a wrapper over countRec. It
// explicitly handles leading digit and calls
// countRec() for remaining digits.
static int finalCount(int n, int sum)
{
// Initialize final answer
int ans = 0;
// Traverse through every digit from 1 to
// 9 and count numbers beginning with it
for (int i = 1; i <= 9; i++)
if (sum-i >= 0)
ans += countRec(n-1, sum-i);
return ans;
}
/* Driver program to test above function */
public static void main (String args[])
{
int n = 2, sum = 5;
System.out.println(finalCount(n, sum));
}
}/* This code is contributed by Rajat Mishra */
Python 3
733
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
# Traverse through every digit and
# count numbers beginning with it
# using recursion
for i in range(0, 10) :
if (sum-i >= 0) :
ans = ans + countRec(n-1, sum-i)
return ans
# This is mainly a wrapper over countRec. It
# explicitly handles leading digit and calls
# countRec() for remaining digits.
def finalCount(n, sum) :
# Initialize final answer
ans = 0
# Traverse through every digit from 1 to
# 9 and count numbers beginning with it
for i in range(1, 10) :
if (sum-i >= 0) :
ans = ans + countRec(n-1, sum-i)
return ans
# Driver program
n = 2
sum = 5
print(finalCount(n, sum))
# This code is contributed by Nikita tiwari.
C#
734
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
735
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
PHP
<?php
// A PHP program using recursive to count numbers
// with sum of digits as given 'sum'
// Recursive function to count 'n' digit numbers
// with sum of digits as 'sum'. This function
// considers leading 0's also as digits, that is
// why not directly called
function countRec($n, $sum)
{
// Base case
if ($n == 0)
return $sum == 0;
if ($sum == 0)
return 1;
// Initialize answer
$ans = 0;
// Traverse through every
// digit and count
// numbers beginning with
// it using recursion
for ($i = 0; $i <= 9; $i++)
if ($sum-$i >= 0)
$ans += countRec($n-1, $sum-$i);
return $ans;
}
// This is mainly a wrapper
// over countRec. It
// explicitly handles leading
// digit and calls
736
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
Output:
The time complexity of above solution is exponential. If we draw the complete recursion
tree, we can observer that many subproblems are solved again and again. For example, if
we start with n = 3 and sum = 10, we can reach n = 1, sum = 8, by considering digit
sequences 1,1 or 2, 0.
Since same suproblems are called again, this problem has Overlapping Subprolems property.
So min square sum problem has both properties (see thisand this) of a dynamic programming
problem.
Below is Memoization based the implementation.
C++
737
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
738
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
// Driver program
int main()
{
int n = 3, sum = 5;
cout << finalCount(n, sum);
return 0;
}
Java
739
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
Output:
15
740
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
int n = 3;
int sum = 5;
findCount(n,sum);
}
private static void findCount(int n, int sum) {
//in case n = 2 start is 10 and end is (100-1) = 99
int start = (int) Math.pow(10, n-1);
int end = (int) Math.pow(10, n)-1;
int count = 0;
int i = start;
while(i < end) {
int cur = 0;
int temp = i;
while( temp != 0) {
cur += temp % 10;
temp = temp / 10;
}
if(cur == sum) {
count++;
i += 9;
}else
i++;
}
System.out.println(count);
/* This code is contributed by Anshuman */
}
}
Output:
15
741
Chapter 95. Count of n digit numbers whose sum of digits equals to given sum
Source
https://www.geeksforgeeks.org/count-of-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum/
742
Chapter 96
where
Examples :
Input : 1
Output : Number of walks possible is/are 0
Explanation :
0 because using just one step we can move to
any of the adjacent cells but we cannot trace
back to the original hexagon.
Input : 2
Output : Number of walks possible is/are 6
Input : 4
Output : Number of walks possible is/are 90
Approach :
• A hexagonal walk can be defined as walking through adjacent hexagons and returning
to the original cell. We know the fact that a hexagon contains six sides i.e. a hexagon
is surrounded by six hexagons. Now, we have to count number of ways we take N
steps and come back to the original hexagon.
743
Chapter 96. Count of possible hexagonal walks
• Now, let us suppose the original hexagon (where element X was initially present) to
be the origin. We need all possible ways we can take (N-k) steps such that we have
some steps which would trace back to our original hexagon. We can visualize this
hexagon and it’s related coordinate system from the picture below.
• Now, let’s assume, our element X was present at 0:0 of the given picture. Thus, we
can travel in six possible directions from a hexagon. Now, using the directions above
we memorize all possible movements such that we trace back to the original 0:0 index.
For memorizing we use a 3D array and we preprocess our answer for a given number
of steps and then query accordingly.
C++
744
Chapter 96. Count of possible hexagonal walks
745
Chapter 96. Count of possible hexagonal walks
int steps = 4;
cout << "Number of walks possible is/are "
<< list[steps] << endl;
return 0;
}
Java
746
Chapter 96. Count of possible hexagonal walks
// This array stores the number of
// ways possible for a given step
list[N] = ways[N][8][8];
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
int list[] = new int[15];
// Preprocessing all possible ways
preprocess(list);
int steps = 4;
System.out.println( "Number of walks"
+ " possible is/are "+
list[steps] );
}
}
C#
// C# implementation of counting
// number of possible hexagonal walks
using System;
class GFG {
static int depth = 14;
static int [, ,]ways = new int[16,16,16];
// static int stepNum;
static void preprocess(int []list)
{
// We initialize our origin with 1
ways[0,8,8] = 1;
// For each N = 1 to 14, we traverse in
// all possible direction. Using this 3D
// array we calculate the number of ways
// at each step and the total ways for a
// given step shall be found at ways[step
// number][8][8] because all the steps
// after that will be used to trace back
// to the original point index 0:0
747
Chapter 96. Count of possible hexagonal walks
Output :
The time complexity of the above code is and the space complexity is
748
Chapter 96. Count of possible hexagonal walks
Source
https://www.geeksforgeeks.org/count-possible-hexagonal-walks/
749
Chapter 97
Count of strings that can be formed using a, b and c under given constraints - GeeksforGeeks
Given a length n, count the number of strings of length n that can be made using ‘a’, ‘b’
and ‘c’ with at-most one ‘b’ and two ‘c’s allowed.
Examples :
Input : n = 3
Output : 19
Below strings follow given constraints:
aaa aab aac aba abc aca acb acc baa
bac bca bcc caa cab cac cba cbc cca ccb
Input : n = 4
Output : 39
750
Chapter 97. Count of strings that can be formed using a, b and c under given constraints
Java
751
Chapter 97. Count of strings that can be formed using a, b and c under given constraints
C#
752
Chapter 97. Count of strings that can be formed using a, b and c under given constraints
PHP
<?php
// PHP program to count number of
// strings of n characters with
// n is total number of characters.
// bCount and cCount are counts
// of 'b' and 'c' respectively.
function countStr($n, $bCount,
$cCount)
{
// Base cases
if ($bCount < 0 ||
$cCount < 0)
return 0;
if ($n == 0)
return 1;
if ($bCount == 0 &&
$cCount == 0)
return 1;
// Three cases, we choose,
// a or b or c. In all three
753
Chapter 97. Count of strings that can be formed using a, b and c under given constraints
Output :
19
Efficient Solution
If we drown a recursion tree of above code, we can notice that same values appear multiple
times. So we store results which are used later if repeated.
C++
754
Chapter 97. Count of strings that can be formed using a, b and c under given constraints
if (n == 0) return 1;
if (bCount == 0 && cCount == 0) return 1;
// if we had saw this combination previously
if (dp[n][bCount][cCount] != -1)
return dp[n][bCount][cCount];
// Three cases, we choose, a or b or c
// In all three cases n decreases by 1.
int res = countStrUtil(dp, n-1, bCount, cCount);
res += countStrUtil(dp, n-1, bCount-1, cCount);
res += countStrUtil(dp, n-1, bCount, cCount-1);
return (dp[n][bCount][cCount] = res);
}
// A wrapper over countStrUtil()
int countStr(int n)
{
int dp[n+1][2][3];
memset(dp, -1, sizeof(dp));
return countStrUtil(dp, n);
}
// Driver code
int main()
{
int n = 3; // Total number of characters
cout << countStr(n);
return 0;
}
Output :
19
755
Chapter 97. Count of strings that can be formed using a, b and c under given constraints
Java
C#
756
Chapter 97. Count of strings that can be formed using a, b and c under given constraints
class GFG
{
static int countStr(int n)
{
return 1 + (n * 2) +
(n * ((n * n) - 1) / 2);
}
// Driver code
static public void Main ()
{
int n = 3;
Console.WriteLine(countStr(n));
}
}
// This code is contributed by m_kit
PHP
<?php
// A O(1) PHP program to find
// number of strings that can
// be made under given constraints.
function countStr($n)
{
return 1 + ($n * 2) + ($n *
(($n * $n) - 1) / 2);
}
// Driver code
$n = 3;
echo countStr($n);
// This code is contributed by aj_36
?>
Output :
19
757
Chapter 97. Count of strings that can be formed using a, b and c under given constraints
Reference :
https://careercup.appspot.com/question?id=5717453712654336
Improved By : jit_t
Source
https://www.geeksforgeeks.org/count-strings-can-formed-using-b-c-given-constraints/
758
Chapter 98
Input : N = 1
Output : Total strings are 26
Explanation : For N=1, strings
are a, b, c,, ...., x, y, z
Input : N = 2
Output : Total strings are 50
Explanation : For N = 2, strings
are ab, ba, bc, cb, .., yx, yz, zy
For strings starting with character ‘A’ and length ‘i’, we consider all strings of length ‘i-1’
and starting with character ‘B’
For strings starting with character ‘G’ and length ‘i’, we consider all strings of length ‘i-1’
and starting with character ‘H’ and all strings of length ‘i-1’ and starting with ‘F’.
We take the base case for n = 1, and set result for all 26 characters as 1. This simply means
when 1 character string is consider all alphabets from a-z are taken only once.
For N = 2,
759
Chapter 98. Count of strings where adjacent characters are of difference one
For N = 3,
Conclusion : For N = n
760
Chapter 98. Count of strings where adjacent characters are of difference one
countAdjacent(n)
dp[i][j] finally stores count of strings
of length i and starting with
character j.
Initialize dp[n+1][27] as 0
Initialize dp[1][j] = 1 where j = 0 to 25
for i = 2 to n
for j = 0 to 25
if (j = 0)
dp[i][j] = dp[i-1][j+1];
else
dp[i][j] = dp[i-1][j-1] + dp[i-1][j+1];
Sum of n-th row from 0 to 25 is the result.
761
Chapter 98. Count of strings where adjacent characters are of difference one
Output:
Source
https://www.geeksforgeeks.org/count-strings-adjacent-characters-difference-one/
762
Chapter 99
The idea is to approach problem by counting subarrays whose maximum element is less than
or equal to k as counting such subarrays is easier. To find the number of subarray whose
maximum element is less than or equal to k, remove all the element which is greater than
K and find the number of subarray with the left elements.
Once we find above count, we can subtract it from n*(n+1)/2 to get our required result.
Observe, there can be n*(n+1)/2 possible number of subarray of any array of size n. So,
finding the number of subarray whose maximum element is less than or equal to K and
substracting it from n*(n+1)/2 gets us the answer.
Below is the implementation of this approach:
C++
763
Chapter 99. Count of subarrays whose maximum element is greater than k
764
Chapter 99. Count of subarrays whose maximum element is greater than k
Java
765
Chapter 99. Count of subarrays whose maximum element is greater than k
int k = 2;
int n = arr.length;
System.out.print(countSubarray(arr, n, k));
}
}
// This code is contributed by Anant Agarwal.
Python3
766
Chapter 99. Count of subarrays whose maximum element is greater than k
C#
767
Chapter 99. Count of subarrays whose maximum element is greater than k
PHP
<?php
// PHP program to count number of subarrays
// whose maximum element is greater than K.
// Return number of subarrays whose maximum
// element is less than or equal to K.
function countSubarray( $arr, $n, $k)
{
// To store count of subarrays with all
// elements less than or equal to k.
$s = 0;
// Traversing the array.
$i = 0;
while ($i < $n) {
// If element is greater than k,
// ignore.
if ($arr[$i] > $k) {
$i++;
768
Chapter 99. Count of subarrays whose maximum element is greater than k
continue;
}
// Counting the subarray length
// whose each element is less
// than equal to k.
$count = 0;
while ($i < $n and $arr[$i] <= $k) {
$i++;
$count++;
}
// Suming number of subarray whose
// maximum element is less than
// equal to k.
$s += (($count * ($count + 1)) / 2);
}
return ($n * ($n + 1) / 2 - $s);
}
// Driven Program
$arr = array( 1, 2, 3 );
$k = 2;
$n = count($arr);
echo countSubarray($arr, $n, $k);
// This code is contributed by anuj_67.
?>
Output:
Source
https://www.geeksforgeeks.org/count-subarrays-whose-maximum-element-greater-k/
769
Chapter 100
N = 1
Output = 4
Place a building on one side.
Place a building on other side
Do not place any building.
Place a building on both sides.
N = 3
Output = 25
3 sections, which means possible ways for one side are
BSS, BSB, SSS, SBS, SSB where B represents a building
and S represents an empty space
Total possible ways are 25, because a way to place on
one side can correspond to any of 5 ways on other side.
N = 4
Output = 64
We strongly recommend to minimize your browser and try this yourself first
We can simplify the problem to first calculate for one side only. If we know the result for
one side, we can always do square of the result and get result for two sides.
770
Chapter 100. Count possible ways to construct buildings
A new building can be placed on a section if section just before it has space. A space can
be placed anywhere (it doesn’t matter whether the previous section has a building or not).
771
Chapter 100. Count possible ways to construct buildings
prev_countB = countB;
prev_countS = countS;
countS = prev_countB + prev_countS;
countB = prev_countS;
}
// Result for one side is sum of ways ending with building
// and ending with space
int result = countS + countB;
// Result for 2 sides is square of result for one side
return (result*result);
}
// Driver program
int main()
{
int N = 3;
cout << "Count of ways for " << N
<< " sections is " << countWays(N);
return 0;
}
Java
class Building
{
// Returns count of possible ways for N sections
static int countWays(int N)
{
// Base case
if (N == 1)
return 4; // 2 for one side and 4 for two sides
// countB is count of ways with a building at the end
// countS is count of ways with a space at the end
// prev_countB and prev_countS are previous values of
// countB and countS respectively.
// Initialize countB and countS for one side
int countB=1, countS=1, prev_countB, prev_countS;
// Use the above recursive formula for calculating
// countB and countS using previous values
for (int i=2; i<=N; i++)
{
prev_countB = countB;
772
Chapter 100. Count possible ways to construct buildings
prev_countS = countS;
countS = prev_countB + prev_countS;
countB = prev_countS;
}
// Result for one side is sum of ways ending with building
// and ending with space
int result = countS + countB;
// Result for 2 sides is square of result for one side
return (result*result);
}
public static void main(String args[])
{
int N = 3;
System.out.println("Count of ways for "+ N+" sections is "
+countWays(N));
}
}/* This code is contributed by Rajat Mishra */
C#
773
Chapter 100. Count possible ways to construct buildings
PHP
774
Chapter 100. Count possible ways to construct buildings
<?php
// PHP program to count all possible
// way to construct buildings
// Returns count of possible
// ways for N sections
function countWays( $N)
{
// Base case
if ($N == 1)
// 2 for one side and
// 4 for two sides
return 4;
// countB is count of ways
// with a building at the end
// countS is count of ways
// with a space at the end
// prev_countB and prev_countS
// are previous values of
// countB and countS respectively.
// Initialize countB and
// countS for one side
$countB = 1; $countS = 1;
$prev_countB; $prev_countS;
// Use the above recursive
// formula for calculating
// countB and countS using
// previous values
for ($i = 2; $i <= $N; $i++)
{
$prev_countB = $countB;
$prev_countS = $countS;
$countS = $prev_countB +
$prev_countS;
$countB = $prev_countS;
}
// Result for one side is
// sum of ways ending with
// building and ending with
// space
$result = $countS + $countB;
775
Chapter 100. Count possible ways to construct buildings
// Result for 2 sides is square
// of result for one side
return ($result*$result);
}
// Driver Code
$N = 3;
echo "Count of ways for " , $N
, " sections is " , countWays($N);
// This code is contributed by anuj_67.
?>
Output :
result(N) = fib(N+2)2
776
Chapter 100. Count possible ways to construct buildings
This article is contributed by GOPINATH. 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
Source
https://www.geeksforgeeks.org/count-possible-ways-to-construct-buildings/
777
Chapter 101
Count the number of ways to tile the floor of size n x m using 1 x m size tiles - GeeksforGeeks
Given a floor of size n x m and tiles of size 1 x m. The problem is to count the number
of ways to tile the given floor using 1 x m tiles. A tile can either be placed horizontally or
vertically.
Both n and m are positive integers and 2 < = m.
Examples:
Input : n = 2, m = 3
Output : 1
Only one combination to place
two tiles of size 1 x 3 horizontally
on the floor of size 2 x 3.
Input : n = 4, m = 4
Output : 2
1st combination:
All tiles are placed horizontally
2nd combination:
All tiles are placed vertically.
778
Chapter 101. Count the number of ways to tile the floor of size n x m using 1 x m size tiles
| 1, 1 < = n < m
count(n) = | 2, n = m
| count(n-1) + count(n-m), m < n
C++
779
Chapter 101. Count the number of ways to tile the floor of size n x m using 1 x m size tiles
return 0;
}
Java
780
Chapter 101. Count the number of ways to tile the floor of size n x m using 1 x m size tiles
// This code is contributed by vt_m.
Python3
# Python implementation to
# count number of ways to
# tile a floor of size n x m
# using 1 x m tiles
def countWays(n, m):
# table to store values
# of subproblems
count =[]
for i in range(n + 2):
count.append(0)
count[0] = 0
# Fill the table upto value n
for i in range(1, n + 1):
# recurrence relation
if (i > m):
count[i] = count[i-1] + count[i-m]
# base cases
elif (i < m):
count[i] = 1
# i = = m
else:
count[i] = 2
# required number of ways
return count[n]
# Driver code
n = 7
m = 4
print("Number of ways = ", countWays(n, m))
# This code is contributed
# by Anant Agarwal.
781
Chapter 101. Count the number of ways to tile the floor of size n x m using 1 x m size tiles
C#
782
Chapter 101. Count the number of ways to tile the floor of size n x m using 1 x m size tiles
}
}
// This code is contributed by parashar.
PHP
<?php
// PHP implementation to count
// number of ways to tile a
// floor of size n x m using
// 1 x m tiles
// function to count the
// total number of ways
function countWays($n, $m)
{
// table to store values
// of subproblems
$count[0] = 0;
// Fill the table
// upto value n
for ($i = 1; $i <= $n; $i++)
{
// recurrence relation
if ($i > $m)
$count[$i] = $count[$i - 1] +
$count[$i - $m];
// base cases
else if ($i < $m)
$count[$i] = 1;
// i = = m
else
$count[$i] = 2;
}
// required number of ways
return $count[$n];
}
// Driver Code
$n = 7;
$m = 4;
783
Chapter 101. Count the number of ways to tile the floor of size n x m using 1 x m size tiles
Output:
Number of ways = 5
Source
https://www.geeksforgeeks.org/count-number-ways-tile-floor-size-n-x-m-using-1-x-m-size-tiles/
784
Chapter 102
Count total number of N digit numbers such that the difference between sum of even and
odd digits is 1 - GeeksforGeeks
Given a number n, we need to count total number of n digit numbers such that the sum
of even digits is 1 more than the sum of odd digits. Here even and odd means positions of
digits are like array indexes, for exampl, the leftmost (or leading) digit is considered as even
digit, next to leftmost is considered as odd and so on.
Example
Input: n = 2
Output: Required Count of 2 digit numbers is 9
Explanation : 10, 21, 32, 43, 54, 65, 76, 87, 98.
Input: n = 3
Output: Required Count of 3 digit numbers is 54
Explanation: 100, 111, 122, ......, 980
We strongly recommend you to minimize your browser and try this yourself
first.
This problem is mainly an extension of Count of n digit numbers whose sum of digits equals
to given sum. Here the solution of subproblems depend on four variables: digits, esum
(current even sum), osum (current odd sum), isEven(A flag to indicate whether current
digit is even or odd).
785
Chapter 102. Count total number of N digit numbers such that the difference between sum
of even and odd digits is 1
786
Chapter 102. Count total number of N digit numbers such that the difference between sum
of even and odd digits is 1
Output:
Source
https://www.geeksforgeeks.org/count-total-number-of-n-digit-numbers-such-that-the-difference-between-the-sum-o
787
Chapter 103
Input : 2
Output : 7
Please see below diagram for explanation.
Input : 3
Output : 17
Following image depicts the 7 possible ways for building the street with N = 2
788
Chapter 103. Count ways to build street under given constraints
For length = 2,
with 2 houses: (H H) can be added to all
the cases of length 1:
(H H) (H H) (H H)
(H H) (O H) (H O) = {3}
(O H) (H O)
(H H) (H H) = {2}
789
Chapter 103. Count ways to build street under given constraints
(O H) (H O) (O O)
(O H) (H O) (O H) etc are not allowed.
Total = 3 + 2 + 2 = 7
Since the problem can be solved by finding solution for smaller subproblems and then
extending the same logic, it can be solved using dynamic programming. We move in steps
of one unit length. For each row we have two options:
Build houses in both the spots
Build one house and one office
The first one can be done without any constraints. There is one way of building houses in
both the spots at length i. So total ways using this choice = total ways for length i – 1.
For the second choice, if row (i-1) had houses in both spots we have two ways of building a
office i.e. (H O) and (O H)
if row(i-1) had an office in one of its two spots we only have one way to build an office in
row i.If prev row had (O H) curr row would have (H O) and similarly for prev row = (H O)
curr row = (O H).
From the above logic, total ways with this choice = 2 * (choice1(i-1)) + choice2(i-1)
We will build a 2D dp for this.
dp[0][i] indicates choice1 and dp[1][i] indicates choice2 for row i.
Below is the implementation of above idea :
C++
790
Chapter 103. Count ways to build street under given constraints
PHP
<?php
// PHP program to count ways to build street
// under given constraints
// function to count ways of building
// a street of n rows
function countWays($n)
{
// base case
$dp[0][1] = 1;
$dp[1][1] = 2;
for ($i = 2; $i <= $n; $i++) {
// ways of building houses in both
// the spots of ith row
$dp[0][$i] = $dp[0][$i - 1] +
$dp[1][$i - 1];
// ways of building an office in one of
// the two spots of ith row
$dp[1][$i] = $dp[0][$i - 1] *
2 + $dp[1][$i - 1];
}
// total ways for n rows
return $dp[0][$n] + $dp[1][$n];
791
Chapter 103. Count ways to build street under given constraints
}
// Driver Code
$n = 5;
echo "Total no of ways with n = ",$n,
" are: " ,countWays($n),"\n";
// This code is contributed by jit_t
?>
Output:
Source
https://www.geeksforgeeks.org/count-ways-build-street-given-constraints/
792
Chapter 104
Input : N = 2
Output : 2
Explanation: If points are numbered 1 to 4 in
clockwise direction, then different ways to
draw chords are:
{(1-2), (3-4)} and {(1-4), (2-3)}
Input : N = 1
Output : 1
Explanation: Draw a chord between points 1 and 2.
If we draw a chord between any two points, can you observe the current set of points
getting broken into two smaller sets S_1 and S_2. If we draw a chord from a point in S_1
to a point in S_2, it will surely intersect the chord we’ve just drawn.
So, we can arrive at a recurrence that Ways(n) = sum[i = 0 to n-1] { Ways(i)*Ways(n-i-1)
}.
Here we iterate over i, assuming that size of one of the sets is i and size of another set
automatically is (n-i-1) since we’ve already used a pair of points and i pair of points in one set.
C++
793
Chapter 104. Count ways to divide circle using N non-intersecting chords
Java
794
Chapter 104. Count ways to divide circle using N non-intersecting chords
class GFG {
static int chordCnt(int A)
{
// n = no of points required
int n = 2 * A;
// dp array containing the sum
int[] dpArray = new int[n + 1];
dpArray[0] = 1;
dpArray[2] = 1;
for (int i = 4; i <= n; i += 2) {
for (int j = 0; j < i - 1; j += 2)
{
dpArray[i] += (dpArray[j] *
dpArray[i - 2 - j]);
}
}
// returning the required number
return dpArray[n];
}
public static void main(String[] args)
{
int N;
N = 2;
System.out.println(chordCnt(N));
N = 1;
System.out.println(chordCnt(N));
N = 4;
System.out.println(chordCnt(N));
}
}
// This code is contributed by Gitanjali.
Python 3
795
Chapter 104. Count ways to divide circle using N non-intersecting chords
dpArray[0] = 1
dpArray[2] = 1
for i in range(4, n + 1, 2):
for j in range(0, i-1, 2):
dpArray[i] += (dpArray[j]*dpArray[i-2-j])
# returning the required number
return int(dpArray[n])
# driver code
N = 2
print(chordCnt( N))
N = 1
print(chordCnt( N))
N = 4
print(chordCnt( N))
C#
796
Chapter 104. Count ways to divide circle using N non-intersecting chords
Output:
2
1
14
Source
https://www.geeksforgeeks.org/count-ways-divide-circle-using-n-non-intersecting-chords/
797
Chapter 105
The idea is try all 26 possible characters at each position of first string, if length of str1
is m then a new character can be inserted in (m + 1) positions, now suppose at any time
character c is inserted at ith position in str1 then we will match it with all positions having
character c in str2. Suppose one such position is j, then for total LCS length to be one more
than previous, below condition should satisfy,
798
Chapter 105. Count ways to increase LCS length of two strings by one
Above equation states that sum of LCS of the suffix and prefix substrings at inserted char-
acter must be same as total LCS of strings, so that when the same character is inserted in
first string it will increase the length of LCS by one.
In below code two 2D arrays, lcsl and lcsr are used for storing LCS of prefix and suffix of
strings respectively. Method for filling these 2D arrays can be found here.
Please see below code for better understanding,
799
Chapter 105. Count ways to increase LCS length of two strings by one
lcsl[i][j-1]);
}
}
// Filling LCS array for suffix substrings
for (int i = m; i >= 1; i--)
{
for (int j = n; j >= 1; j--)
{
if (str1[i-1] == str2[j-1])
lcsr[i][j] = 1 + lcsr[i+1][j+1];
else
lcsr[i][j] = max(lcsr[i+1][j],
lcsr[i][j+1]);
}
}
// Looping for all possible insertion positions
// in first string
int ways = 0;
for (int i=0; i<=m; i++)
{
// Trying all possible lower case characters
for (char c='a'; c<='z'; c++)
{
// Now for each character, loop over same
// character positions in second string
for (int j=0; j<position[toInt(c)].size(); j++)
{
int p = position[toInt(c)][j];
// If both, left and right substrings make
// total LCS then increase result by 1
if (lcsl[i][p-1] + lcsr[i+1][p+1] == lcsl[m][n])
ways++;
}
}
}
return ways;
}
// Driver code to test above methods
int main()
{
string str1 = "abcabc";
string str2 = "abcd";
cout << waysToIncreaseLCSBy1(str1, str2);
800
Chapter 105. Count ways to increase LCS length of two strings by one
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/count-ways-increase-lcs-length-two-strings-one/
801
Chapter 106
Input : 4
Output : 7
Input : 3
Output : 4
1. Recursive Method
How Code is Working :
Suppose you have n stairs then you can hop either 1 step, 2 step, 3 step.
1. If you hop 1 step then remaining stairs = n-1
2. If you hop 2 step then remaining stairs = n-2
3. If you hop 3 step then remaining stairs = n-3
If you hop 1 step then again you can hop 1 step, 2 step, 3 step until n equals 0.
Repeat this process and count total number of ways to reach at nth stair using step 1, 2, 3.
802
Chapter 106. Count ways to reach the nth stair using step 1, 2 or 3
Java
803
Chapter 106. Count ways to reach the nth stair using step 1, 2 or 3
findStep(n - 1);
}
// Driver function
public static void main(String argc[]){
int n = 4;
System.out.println(findStep(n));
}
}
/* This code is contributed by Sagar Shukla */
Python
C#
804
Chapter 106. Count ways to reach the nth stair using step 1, 2 or 3
if (n == 1 || n == 0)
return 1;
else if (n == 2)
return 2;
else
return findStep(n - 3) +
findStep(n - 2) +
findStep(n - 1);
}
// Driver function
public static void Main(){
int n = 4;
Console.WriteLine(findStep(n));
}
}
/* This code is contributed by vt_m */
PHP
<?php
// PHP Program to find n-th stair
// using step size 1 or 2 or 3.
// Returns count of ways to
// reach n-th stair using
// 1 or 2 or 3 steps.
function findStep($n)
{
if ($n == 1 || $n == 0)
return 1;
else if ($n == 2)
return 2;
else
return findStep($n - 3) +
findStep($n - 2) +
findStep($n - 1);
}
// Driver code
$n = 4;
echo findStep($n);
// This code is contributed by m_kit
?>
805
Chapter 106. Count ways to reach the nth stair using step 1, 2 or 3
Output :
806
Chapter 106. Count ways to reach the nth stair using step 1, 2 or 3
Java
807
Chapter 106. Count ways to reach the nth stair using step 1, 2 or 3
for (int i = 3; i <= n; i++)
res[i] = res[i - 1] + res[i - 2]
+ res[i - 3];
return res[n];
}
// Driver function
public static void main(String argc[])
{
int n = 4;
System.out.println(countWays(n));
}
}
/* This code is contributed by Sagar Shukla */
Python
C#
808
Chapter 106. Count ways to reach the nth stair using step 1, 2 or 3
public class GfG {
// A recursive function used by countWays
public static int countWays(int n)
{
int[] res = new int[n + 1];
res[0] = 1;
res[1] = 1;
res[2] = 2;
for (int i = 3; i <= n; i++)
res[i] = res[i - 1] + res[i - 2]
+ res[i - 3];
return res[n];
}
// Driver function
public static void Main()
{
int n = 4;
Console.WriteLine(countWays(n));
}
}
/* This code is contributed by vt_m */
PHP
<?php
// A PHP program to count
// number of ways to reach
// n'th stair when
// A recursive function
// used by countWays
function countWays($n)
{
$res[0] = 1;
$res[1] = 1;
$res[2] = 2;
for ($i = 3; $i <= $n; $i++)
$res[$i] = $res[$i - 1] +
$res[$i - 2] +
$res[$i - 3];
return $res[$n];
809
Chapter 106. Count ways to reach the nth stair using step 1, 2 or 3
}
// Driver Code
$n = 4;
echo countWays($n);
// This code is contributed by ajit
?>
Output :
Output Explanation :
1 -> 1 -> 1 -> 1
1 -> 1 -> 2
1 -> 2 -> 1
1 -> 3
2 -> 1 -> 1
2 -> 2
3 -> 1
So Total ways: 7
Other Related Articles
http://www.geeksforgeeks.org/count-ways-reach-nth-stair/
Improved By : jit_t
Source
https://www.geeksforgeeks.org/count-ways-reach-nth-stair-using-step-1-2-3/
810
Chapter 107
Consider the example shown in diagram. The value of n is 3. There are 3 ways to reach the
top. The diagram is taken from Easier Fibonacci puzzles
More Examples:
811
Chapter 107. Count ways to reach the n’th stair
Input: n = 1
Output: 1
There is only one way to climb 1 stair
Input: n = 2
Output: 2
There are two ways: (1, 1) and (2)
Input: n = 4
Output: 5
(1, 1, 1, 1), (1, 1, 2), (2, 1, 1), (1, 2, 1), (2, 2)
We can easily find recursive nature in above problem. The person can reach n’th stair from
either (n-1)’th stair or from (n-2)’th stair. Let the total number of ways to reach n’t stair
be ‘ways(n)’. The value of ‘ways(n)’ can be written as following.
The above expression is actually the expression for Fibonacci numbers, but there is one
thing to notice, the value of ways(n) is equal to fibonacci(n+1).
ways(1) = fib(2) = 1
ways(2) = fib(3) = 2
ways(3) = fib(4) = 3
So we can use function for fibonacci numbers to find the value of ways(n). Following is
C++ implementation of the above idea.
812
Chapter 107. Count ways to reach the n’th stair
// Driver program to test above functions
int main ()
{
int s = 4;
printf("Number of ways = %d", countWays(s));
getchar();
return 0;
}
Java
class stairs
{
// A simple recursive program to find n'th fibonacci number
static int fib(int n)
{
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
// Returns number of ways to reach s'th stair
static int countWays(int s)
{
return fib(s + 1);
}
/* Driver program to test above function */
public static void main (String args[])
{
int s = 4;
System.out.println("Number of ways = "+ countWays(s));
}
}/* This code is contributed by Rajat Mishra */
Python
813
Chapter 107. Count ways to reach the n’th stair
C#
814
Chapter 107. Count ways to reach the n’th stair
PHP
<?php
// A PHP program to count
// number of ways to reach
// n'th stair when a person
// can climb 1, 2, ..m stairs
// at a time.
// A simple recursive
// function to find n'th
// fibonacci number
function fib($n)
{
if ($n <= 1)
return $n;
return fib($n - 1) +
fib($n - 2);
}
// Returns number of
// ways to reach s'th stair
function countWays($s)
{
return fib($s + 1);
}
// Driver Code
$s = 4;
echo "Number of ways = ",
countWays($s);
// This code is contributed
// by m_kit
?>
Output:
Number of ways = 5
The time complexity of the above implementation is exponential (golden ratio raised to
power n). It can be optimized to work in O(Logn) time using the previously discussed
Fibonacci function optimizations.
815
Chapter 107. Count ways to reach the n’th stair
Java
class stairs
{
816
Chapter 107. Count ways to reach the n’th stair
Python
817
Chapter 107. Count ways to reach the n’th stair
C#
PHP
<?php
// A PHP program to count
818
Chapter 107. Count ways to reach the n’th stair
Output:
Number of ways = 5
819
Chapter 107. Count ways to reach the n’th stair
// A recursive function used by countWays
int countWaysUtil(int n, int m)
{
int res[n];
res[0] = 1; res[1] = 1;
for (int i=2; i<n; i++)
{
res[i] = 0;
for (int j=1; j<=m && j<=i; j++)
res[i] += res[i-j];
}
return res[n-1];
}
// Returns number of ways to reach s'th stair
int countWays(int s, int m)
{
return countWaysUtil(s+1, m);
}
// Driver program to test above functions
int main ()
{
int s = 4, m = 2;
printf("Nuber of ways = %d", countWays(s, m));
return 0;
}
Java
820
Chapter 107. Count ways to reach the n’th stair
}
// Returns number of ways to reach s'th stair
static int countWays(int s, int m)
{
return countWaysUtil(s+1, m);
}
// Driver method
public static void main(String[] args)
{
int s = 4, m = 2;
System.out.println("Nuber of ways = " + countWays(s, m));
}
}
Python
C#
821
Chapter 107. Count ways to reach the n’th stair
// stairs at a time
using System;
class GFG {
// A recursive function
// used by countWays
static int countWaysUtil(int n, int m)
{
int []res = new int[n];
res[0] = 1; res[1] = 1;
for (int i = 2; i < n; i++)
{
res[i] = 0;
for (int j = 1; j <= m && j <= i; j++)
res[i] += res[i - j];
}
return res[n - 1];
}
// Returns number of ways
// to reach s'th stair
static int countWays(int s, int m)
{
return countWaysUtil(s + 1, m);
}
// Driver Code
public static void Main()
{
int s = 4, m = 2;
Console.WriteLine("Number of ways = " + countWays(s, m));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// A PHP program to count number
// of ways to reach n't stair when
// a person can climb 1, 2, ..m
// stairs at a time
// A recursive function used by countWays
function countWaysUtil($n, $m)
{
$res[0] = 1; $res[1] = 1;
822
Chapter 107. Count ways to reach the n’th stair
Output:
Number of ways = 5
This article is contributed by Abhishek. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : jit_t, vt_m, nitin mittal, Saurabh Vemuri
Source
https://www.geeksforgeeks.org/count-ways-reach-nth-stair/
823
Chapter 108
.
Write a program which takes positive number n on input and returns number of decimal
numbers of length n that are monotone. Numbers can’t start with 0.
Examples :
Input : 1
Output : 9
Numbers are 1, 2, 3, ... 9
Input : 2
Output : 45
Numbers are 11, 12, 13, .... 22, 23
...29, 33, 34, ... 39.
Count is 9 + 8 + 7 ... + 1 = 45
All those numbers are monotone as each digit on higher place is than the one before it.
What are the monotone numbers are of length 1 and digits 1 or 2? It is question to ask
yourself at the very beginning. We can see that possible numbers are:
824
Chapter 108. Counting numbers of n digits that are monotone
That was easy, now lets expand the question to digits 1, 2 and 3:
Now different question, what are the different monotone numbers consisting of only 1 and
length 3 are there?
Lets try now draw this very simple observation in 2 dimensional array for number of length
3, where first column is the length of string and first row is possible digits:
Let’s try to fill 3rd row 3rd column(number of monotone numbers consisting from numbers
825
Chapter 108. Counting numbers of n digits that are monotone
C++
Java
826
Chapter 108. Counting numbers of n digits that are monotone
Python3
827
Chapter 108. Counting numbers of n digits that are monotone
C#
828
Chapter 108. Counting numbers of n digits that are monotone
{
// DP[i][j] is going to store
// monotone numbers of length
// i+1 considering j+1 digits.
int[,] DP = new int[len,DP_s];
// Unit length numbers
for (int i = 0; i < DP_s; ++i)
DP[0,i] = i + 1;
// Single digit numbers
for (int i = 0; i < len; ++i)
DP[i,0] = 1;
// Filling rest of the entries
// in bottom up manner.
for (int i = 1; i < len; ++i)
for (int j = 1; j < DP_s; ++j)
DP[i,j] = DP[i - 1,j]
+ DP[i,j - 1];
return DP[len - 1,DP_s - 1];
}
// Driver code.
public static void Main ()
{
Console.WriteLine(getNumMonotone(10));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to count numbers
// of n digits that are monotone.
function getNumMonotone($len)
{
// Considering all possible
// digits as {1, 2, 3, ..9}
$DP_s = 9;
// DP[i][j] is going to store
// monotone numbers of length
829
Chapter 108. Counting numbers of n digits that are monotone
Output :
43758
Source
https://www.geeksforgeeks.org/counting-numbers-n-digits-monotone/
830
Chapter 109
Counting pairs when a person can form pair with at most one - GeeksforGeeks
Consider a coding competition on geeksforgeeks practice. Now their are n distinct partici-
pants taking part in the competition. A single participant can make pair with at most one
other participant. We need count the number of ways in which n participants participating
in the coding competition.
Examples :
Input : n = 2
Output : 2
2 shows that either both participant
can pair themselves in one way or both
of them can remain single.
Input : n = 3
Output : 4
One way : Three participants remain single
Three More Ways : [(1, 2)(3)], [(1), (2,3)]
and [(1,3)(2)]
1) Every participant can either pair with another participant or can remain single.
2) Let us consider X-th participant, he can either remain single or
he can pair up with someone from [1, x-1].
C++
831
Chapter 109. Counting pairs when a person can form pair with at most one
Java
832
Chapter 109. Counting pairs when a person can form pair with at most one
return numberOfWays(x-1) +
(x-1)*numberOfWays(x-2);
}
// Driver code
public static void main (String[] args) {
int x = 3;
System.out.println( numberOfWays(x));
}
}
// This code is contributed by vt_m.
Python3
C#
833
Chapter 109. Counting pairs when a person can form pair with at most one
class GFG {
static int numberOfWays(int x)
{
// Base condition
if (x == 0 || x == 1)
return 1;
// A participant can choose to
// consider (1) Remains single.
// Number of people reduce to
// (x-1) (2) Pairs with one of
// the (x-1) others. For every
// pairing, number of people
// reduce to (x-2).
else
return numberOfWays(x - 1) +
(x - 1) * numberOfWays(x - 2);
}
// Driver code
public static void Main ()
{
int x = 3;
Console.WriteLine(numberOfWays(x));
}
}
// This code is contributed by vt_m.
PHP
<?php
// Number of ways in which
// participant can take part.
function numberOfWays($x)
{
// Base condition
if ($x == 0 || $x == 1)
return 1;
// A participant can choose
// to consider (1) Remains single.
// Number of people reduce to (x-1)
834
Chapter 109. Counting pairs when a person can form pair with at most one
Output :
C++
835
Chapter 109. Counting pairs when a person can form pair with at most one
Java
Python3
836
Chapter 109. Counting pairs when a person can form pair with at most one
(x-1) * numberOfWays(x-2))
# Driver code
x = 3
print (numberOfWays(x))
# This code is contributed by "Sharad_Bhardwaj"
C#
PHP
<?php
// PHP program for Number of ways
// in which participant can take part.
function numberOfWays($x)
{
837
Chapter 109. Counting pairs when a person can form pair with at most one
$dp[0] = 1;
$dp[1] = 1;
for ($i = 2; $i <= $x; $i++)
$dp[$i] = $dp[$i - 1] + ($i - 1) *
$dp[$i - 2];
return $dp[$x];
}
// Driver code
$x = 3;
echo numberOfWays($x) ;
// This code is contributed by Sam007
?>
Output:
Source
https://www.geeksforgeeks.org/counting-pairs-person-can-form-pair-one/
838
Chapter 110
Input : 3 6
Output : Number of Paths 84
Input : 3 0
Output : Number of Paths 1
839
Chapter 110. Counts paths from a point to reach Origin
As we are restricted to move down and left only we would run a recursive loop for each of
the combinations of the
steps that can be taken.
840
Chapter 110. Counts paths from a point to reach Origin
C++
Java
841
Chapter 110. Counts paths from a point to reach Origin
return 1;
// Else count sum of both ways
return (countPaths(n - 1, m) + countPaths(n, m - 1));
}
// Driver Code
public static void main (String[] args)
{
int n = 3, m = 2;
System.out.println (" Number of Paths "
+ countPaths(n, m));
}
}
// This code is contributed by vt_m
Python3
C#
842
Chapter 110. Counts paths from a point to reach Origin
PHP
<?php
// PHP program to count total number
// of paths from a point to origin
// Recursive function to
// count number of paths
function countPaths($n, $m)
{
// If we reach bottom or
// top left, we are
// have only one way to
843
Chapter 110. Counts paths from a point to reach Origin
Output:
Number of Paths 10
We can use Dynamic Programming as there are overlapping subproblems. We can draw
recursion tree to see overlapping problems. For example, in case of countPaths(4, 4), we
compute countPaths(3, 3) multiple times.
C++
844
Chapter 110. Counts paths from a point to reach Origin
Java
845
Chapter 110. Counts paths from a point to reach Origin
}
}
// This code is contributed by vt_m
C#
846
Chapter 110. Counts paths from a point to reach Origin
PHP
<?php
// PHP program to count total number of
// paths from a point to origin
// DP based function to
// count number of paths
function countPaths($n, $m)
{
//$dp[$n+1][$m+1];
// Fill entries in bottommost
// row and leftmost columns
for ($i = 0; $i <= $n; $i++)
$dp[$i][0] = 1;
for ($i = 0; $i <= $m; $i++)
$dp[0][$i] = 1;
// Fill DP in bottom up manner
for ($i = 1; $i <= $n; $i++)
for ($j = 1; $j <= $m; $j++)
$dp[$i][$j] = $dp[$i - 1][$j] +
$dp[$i][$j - 1];
return $dp[$n][$m];
}
// Driver Code
$n = 3;
$m = 2;
echo " Number of Paths " , countPaths($n, $m);
// This code is contributed by m_kit
?>
Output:
Number of Paths 10
Source
https://www.geeksforgeeks.org/counts-paths-point-reach-origin/
847
Chapter 111
Delannoy Number
Examples :
Input : n = 3, m = 3
Output : 63
848
Chapter 111. Delannoy Number
Input : n = 4, m = 5
Output : 681
C++
Java
849
Chapter 111. Delannoy Number
// Recursive step.
return dealnnoy(m - 1, n) +
dealnnoy(m - 1, n - 1) +
dealnnoy(m, n - 1);
}
// driver function
public static void main(String args[]){
int n = 3, m = 4;
System.out.println(dealnnoy(n, m));
}
}
/* This code is contributed by Sagar Shukla. */
Python3
C#
850
Chapter 111. Delannoy Number
{
// Base case
if (m == 0 || n == 0)
return 1;
// Recursive step.
return dealnnoy(m - 1, n) +
dealnnoy(m - 1, n - 1) +
dealnnoy(m, n - 1);
}
// driver function
public static void Main()
{
int n = 3, m = 4;
Console.WriteLine(dealnnoy(n, m));
}
}
/* This code is contributed by vt_m. */
PHP
<?php
// PHP Program of finding nth
// Delannoy Number.
// Return the nth Delannoy Number.
function dealnnoy( $n, $m)
{
// Base case
if ($m == 0 or $n == 0)
return 1;
// Recursive step.
return dealnnoy($m - 1, $n) +
dealnnoy($m - 1, $n - 1) +
dealnnoy($m, $n - 1);
}
// Driver Code
$n = 3;
$m = 4;
echo dealnnoy($n, $m);
// This code is contributed by anuj_67.
851
Chapter 111. Delannoy Number
?>
Output:
129
C++
Java
852
Chapter 111. Delannoy Number
import java.io.*;
class GFG {
// Return the nth Delannoy Number.
static int dealnnoy(int n, int m)
{
int dp[][]=new int[m + 1][n + 1];
// Base cases
for (int i = 0; i <= m; i++)
dp[i][0] = 1;
for (int i = 0; i < m; i++)
dp[0][i] = 1;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = dp[i - 1][j] +
dp[i - 1][j - 1] +
dp[i][j - 1];
return dp[m][n];
}
// Driven Program
public static void main(String args[])
{
int n = 3, m = 4;
System.out.println(dealnnoy(n, m));
}
}
// This code is contributed by Nikita Tiwari.
Python3
853
Chapter 111. Delannoy Number
for i in range(1, m + 1):
dp[i][0] = 1
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + dp[i][j - 1];
return dp[m][n]
# Driven code
n = 3
m = 4
print(dealnnoy(n, m))
# This code is contributed by "rishabh_jain".
C#
854
Chapter 111. Delannoy Number
int n = 3, m = 4;
Console.WriteLine(dealnnoy(n, m));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program of finding
// nth Delannoy Number.
// Return the nth Delannoy Number.
function dealnnoy($n, $m)
{
$dp[$m + 1][$n + 1] = 0;
// Base cases
for ($i = 0; $i <= $m; $i++)
$dp[$i][0] = 1;
for ( $i = 0; $i <= $m; $i++)
$dp[0][$i] = 1;
for ($i = 1; $i <= $m; $i++)
for ($j = 1; $j <= $n; $j++)
$dp[$i][$j] = $dp[$i - 1][$j] +
$dp[$i - 1][$j - 1] +
$dp[$i][$j - 1];
return $dp[$m][$n];
}
// Driven Code
$n = 3; $m = 4;
echo dealnnoy($n, $m) ;
// This code is contributed by SanjuTomar
?>
Output :
129
855
Chapter 111. Delannoy Number
Source
https://www.geeksforgeeks.org/delannoy-number/
856
Chapter 112
Input : n = 3, m = 1
Output : 3
Following are three different ways
to get sum n such that each term is
greater than or equal to m
1 + 1 + 1, 1 + 2, 3
Input : n = 2, m = 1
Output : 2
Two ways are 1 + 1 and 2
The idea is to use Dynamic Programming by define 2D matrix, say dp[][]. dp[i][j] define
the number of ways to get sum i using the numbers greater than or equal to j. So dp[i][j]
can be defined as:
857
Chapter 112. Different ways to sum n using numbers greater than or equal to m
CPP
858
Chapter 112. Different ways to sum n using numbers greater than or equal to m
// Driver Program
int main()
{
int n = 3, m = 1;
cout << numberofways(n, m) << endl;
return 0;
}
Java
859
Chapter 112. Different ways to sum n using numbers greater than or equal to m
C#
860
Chapter 112. Different ways to sum n using numbers greater than or equal to m
Output:
Source
https://www.geeksforgeeks.org/different-ways-sum-n-using-numbers-greater-equal-m/
861
Chapter 113
Digit DP | Introduction
• Let given number x has n digits. The main idea of digit DP is to first represent the
digits as an array of digits t[]. Let’s say a we have tn tn-1 tn-2 … t2 t1 as the decimal
representation where ti (0 < i <= n) tells the i-th digit from the right. The leftmost
digit tn is the most significant digit.
• Now, after representing the given number this way we generate the numbers less than
the given number and simultaneously calculate using DP, if the number satisfy the
given property. We start generating integers having number of digits = 1 and
then till number of digits = n. Integers having less number of digits than
n can be analyzed by setting the leftmost digits to be zero.
Example Problem :
Given to integers a and b. Your task is to print the sum of
all the digits appearing in the integers between a and b.
For example if a = 5 and b = 11, then answer is 38 (5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 + 1)
Constraints : 1 <= a < b <= 10^18
Now we see that if we have calculated the answer for state having n-1 digits, i.e., tn-1 tn-2
… t2 t1 and we need to calculate answer for state having n digitdtn tn-1 tn-2 … t2 t1 . So,
862
Chapter 113. Digit DP | Introduction
clearly, we can use the result of the previous state instead of re-calculating it. Hence, it
follows the overlapping property.
Let’s think for a state for this DP
Our DP state will be dp(idx, tight, sum)
1) idx
• It tells about the index value from right in the given integer
2) tight
• This will tell if the current digits range is restricted or not. If the current digit’s
range is not restricted then it will span from 0 to 9 (inclusively) else it will span
from 0 to digit[idx] (inclusively).
Example: consider our limiting integer to be 3245 and we need to calculate G(3245)
index : 4 3 2 1
digits : 3 2 4 5
Unrestricted range:
Now suppose the integer generated till now is : 3 1 * * ( * is empty place, where digits are
to be inserted to form the integer).
index : 4 3 2 1
digits : 3 2 4 5
generated integer: 3 1 _ _
here, we see that index 2 has unrestricted range. Now index 2 can have digits from range 0
to 9(inclusively).
For unrestricted range tight = 0
Restricted range:
Now suppose the integer generated till now is : 3 2 * * ( ‘*’ is an empty place, where digits
are to be inserted to form the integer).
index : 4 3 2 1
digits : 3 2 4 5
generated integer: 3 2 _ _
here, we see that index 2 has a restricted range. Now index 2 can only have digits from
range 0 to 4 (inclusively)
For unrestricted range tight = 1
3) sum
863
Chapter 113. Digit DP | Introduction
• This parameter will store the sum of digits in the generated integer from msd to idx.
• Max value for this parameter sum can be 9*18 = 162, considering 18 digits in the
integer
State Relation
The basic idea for state relation is very simple. We formulate the dp in top-down fashion.
Let’s say we are at the msd having index idx. So initially sum will be 0.
Therefore, we will fill the digit at index by the digits in its range. Let’s say its range is
from 0 to k (k<=9, depending on the tight value) and fetch the answer from the next state
having index = idx-1 and sum = previous sum + digit chosen.
int ans = 0;
for (int i=0; i<=k; i++) {
ans += state(idx-1, newTight, sum+i)
}
state(idx,tight,sum) = ans;
864
Chapter 113. Digit DP | Introduction
// Stores the digits in x in a vector digit
long long getDigits(long long x, vector <int> &digit)
{
while (x)
{
digit.push_back(x%10);
x /= 10;
}
}
// Return sum of digits from 1 to integer in
// digit vector
long long digitSum(int idx, int sum, int tight,
vector <int> &digit)
{
// base case
if (idx == -1)
return sum;
// checking if already calculated this state
if (dp[idx][sum][tight] != -1 and tight != 1)
return dp[idx][sum][tight];
long long ret = 0;
// calculating range value
int k = (tight)? digit[idx] : 9;
for (int i = 0; i <= k ; i++)
{
// caclulating newTight value for next state
int newTight = (digit[idx] == i)? tight : 0;
// fetching answer from next state
ret += digitSum(idx-1, sum+i, newTight, digit);
}
if (!tight)
dp[idx][sum][tight] = ret;
return ret;
}
// Returns sum of digits in numbers from a to b.
int rangeDigitSum(int a, int b)
{
// initializing dp with -1
865
Chapter 113. Digit DP | Introduction
Output:
Time Complexity:
There are total idx*sum*tight states and we are performing 0 to 9 iterations to visit every
state. Therefore, The Time Complexity will be O(10*idx*sum*tight). Here, we observe
that tight = 2 and idx can be max 18 for 64 bit unsigned integer and moreover, the sum
will be max 9*18 ~ 200. So, overall we have 10*18*200*2 ~ 10^5 iterations which can be
easily executed in 0.01 seconds.
The above problem can also be solved using simple recursion without any memoization. The
recursive solution for the above problem can be found here. We will be soon adding more
problems on digit dp in our future posts.
Improved By : sauravtygg
866
Chapter 113. Digit DP | Introduction
Source
https://www.geeksforgeeks.org/digit-dp-introduction/
867
Chapter 114
Dynamic Programming on
Trees | Set 2
The above diagram represents a tree with 11 nodes and 10 edges, and the path which
gives us the maximum height when node 1 is considered as root. The maximum height is 3.
868
Chapter 114. Dynamic Programming on Trees | Set 2
In the above diagram, when 2 is considered as root, then the longest path found is in RED
color. A naive approach will be to traverse the tree using DFS traversal for every node
and calculate the maximum height when the node is treated as the root of the tree. The
time complexity for DFS traversal of a tree is O(N). The overall time complexity of
DFS for all N nodes will be O(N)*N i.e., O(N2 ).
The above problem can be solved by using Dynamic Programming on Trees. To solve
this problem, pre-calculate two things for every node. One will be the maximum height while
traveling downwards via its branches to the leaves. While the other will be the maximum
height when traveling upwards via its parent to any of the leaves.
Optimal Substructure :
When node i is considered as root,
in[i] be the maximum height of tree when we travel downwards via its sub-trees and leaves.
Also, out[i] be the maximum height of the tree while traveling upwards via its parent.
Calculation of in[i] :
869
Chapter 114. Dynamic Programming on Trees | Set 2
In the image above, values of in[i] have been calculated for every node i. The maximum of
every subtree is taken and added with 1 to the parent of that subtree. Add 1 for the edge
between parent and subtree. Traverse the tree using DFS and calculate in[i] as max(in[i],
1+in[child]) for every node.
Calculation of out[i] :
The above diagram shows all the out[i] values and the path. For calculation of out[i], move
upwards to the parent of node i. From the parent of node i, there are two ways to move in,
one will be in all the branches of the parent. The other direction is to move to the parent(call
it parent2 to avoid confusion) of the parent(call it parent1) of node i. The maximum height
upwards via parent2 is out[parent1] itself. Generally, out[node i] as 1+max(out[i], 1+max
870
Chapter 114. Dynamic Programming on Trees | Set 2
of all branches). Add 1 for the edges between node and parent.
The above diagram explains the calculation of out[i] when 2 is considered as the root of the
tree. The branches of node 2 is not taken into count since the maximum height via that
path has already been calculated and stored in i[2]. Moving up, in this case, the parent of 2
i.e., 1 has no parent. So, the branches except for the one which has the node are considered
while calculating the maximum.
The above diagram explains the calculation of out[10]. The parent of node 10, i.e., 7 has
a parent and a branch(precisely a child in this case). So the maximum height of both has
been taken to count in such cases when parent and branches exist.
871
Chapter 114. Dynamic Programming on Trees | Set 2
C++
872
Chapter 114. Dynamic Programming on Trees | Set 2
873
Chapter 114. Dynamic Programming on Trees | Set 2
}
// fucntion to print all the maximum heights
// from every node
void printHeights(vector<int> v[], int n)
{
// traversal to calculate in[] array
dfs1(v, 1, 0);
// traversal to calculate out[] array
dfs2(v, 1, 0);
// print all maximum heights
for (int i = 1; i <= n; i++)
cout << "The maximum height when node "
<< i << " is considered as root"
<< " is " << max(in[i], out[i])
<< "\n";
}
// Driver Code
int main()
{
int n = 11;
vector<int> v[n + 1];
// initialize the tree given in the diagram
v[1].push_back(2), v[2].push_back(1);
v[1].push_back(3), v[3].push_back(1);
v[1].push_back(4), v[4].push_back(1);
v[2].push_back(5), v[5].push_back(2);
v[2].push_back(6), v[6].push_back(2);
v[3].push_back(7), v[7].push_back(3);
v[7].push_back(10), v[10].push_back(7);
v[7].push_back(11), v[11].push_back(7);
v[4].push_back(8), v[8].push_back(4);
v[4].push_back(9), v[9].push_back(4);
// function to print the maximum height from every node
printHeights(v, n);
return 0;
}
Output :
874
Chapter 114. Dynamic Programming on Trees | Set 2
Source
https://www.geeksforgeeks.org/dynamic-programming-trees-set-2/
875
Chapter 115
Dynamic Programming on
Trees | Set-1
876
Chapter 115. Dynamic Programming on Trees | Set-1
Given above is a diagram of a tree with N=14 nodes and N-1=13 edges. The values at
node being 3, 2, 1, 10, 1, 3, 9, 1, 5, 3, 4, 5, 9 and 8 respectively for nodes 1, 2, 3,
4….14.
The diagram below shows all the paths from root to leaves :
877
Chapter 115. Dynamic Programming on Trees | Set-1
first level, 10 from the next level and 5 from the third level greedily. Result is path-7 if after
following greedy approach, hence do not apply greedy approach over here.
The problem can be solved using Dynamic Programming on trees. Start memoizing
from the leaves and add the maximum of leaves to the root of every sub-tree. At the last
step, there will be root and the sub-tree under it, adding the value at node and maximum
of sub-tree will give us the maximum sum of the node values from root to any of the leaves.
The diagram above shows how to start from the leaves and add the maximum of
leaves of a sub-tree to its root. Move upward and repeat the same procedure of storing
the maximum of every sub-tree leaves and adding it to its root. In this example, the
maximum of node 11 and 12 is taken to count and then added to node 5(In this sub-tree,
5 is the root and 11, 12 are its leaves). Similarly, the maximum of node 13 and 15 is
taken to count and then added to node 7. Repeat the steps for every sub-tree till we reach
the node.
Let DPi be the maximum summation of node values in the path between i and any of its
leaves moving downwards. Traverse the tree using DFS traversal. Store the maximum
878
Chapter 115. Dynamic Programming on Trees | Set-1
of all the leaves of the sub-tree, and add it to the root of the sub-tree. At the end, DP1 will
have the maximum sum of the node values from root to any of the leaves without re-visiting
any node.
Below is the implementation of the above idea :
CPP
879
Chapter 115. Dynamic Programming on Trees | Set-1
return dp[1];
}
// Driver Code
int main()
{
// number of nodes
int n = 14;
// adjacency list
vector<int> v[n + 1];
// create undirected edges
// initialize the tree given in the diagram
v[1].push_back(2), v[2].push_back(1);
v[1].push_back(3), v[3].push_back(1);
v[1].push_back(4), v[4].push_back(1);
v[2].push_back(5), v[5].push_back(2);
v[2].push_back(6), v[6].push_back(2);
v[3].push_back(7), v[7].push_back(3);
v[4].push_back(8), v[8].push_back(4);
v[4].push_back(9), v[9].push_back(4);
v[4].push_back(10), v[10].push_back(4);
v[5].push_back(11), v[11].push_back(5);
v[5].push_back(12), v[12].push_back(5);
v[7].push_back(13), v[13].push_back(7);
v[7].push_back(14), v[14].push_back(7);
// values of node 1, 2, 3....14
int a[] = { 3, 2, 1, 10, 1, 3, 9, 1, 5, 3, 4, 5, 9, 8 };
// function call
cout << maximumValue(a, v);
return 0;
}
Output:
22
Source
https://www.geeksforgeeks.org/dynamic-programming-trees-set-1/
880
Chapter 116
Dynamic Programming vs
Divide-and-Conquer
The Problem
When I started to learn algorithms it was hard for me to understand the main idea of
dynamic programming (DP) and how it is different from divide-and-conquer (DC) approach.
When it gets to comparing those two paradigms usually Fibonacci function comes to the
rescue as great example. But when we’re trying to solve the same problem using both DP
and DC approaches to explain each of them, it feels for me like we may lose valuable detail
that might help to catch the difference faster. And these detail tells us that each technique
serves best for different types of problems.
I’m still in the process of understanding DP and DC difference and I can’t say that I’ve fully
grasped the concepts so far. But I hope this article will shed some extra light and help you
to do another step of learning such valuable algorithm paradigms as dynamic programming
and divide-and-conquer.
As I see it for now I can say that dynamic programming is an extension of divide and conquer
paradigm.
I would not treat them as something completely different. Because they both work by
recursively breaking down a problem into two or more sub-problems of the same or related
881
Chapter 116. Dynamic Programming vs Divide-and-Conquer
type, until these become simple enough to be solved directly. The solutions to the sub-
problems are then combined to give a solution to the original problem.
So why do we still have different paradigm names then and why I called dynamic program-
ming an extension. It is because dynamic programming approach may be applied to the
problem only if the problem has certain restrictions or prerequisites. And after that dy-
namic programming extends divide and conquer approach with memoization or tabulation
technique.
Let’s go step by step…
As we’ve just discovered there are two key attributes that divide and conquer problem must
have in order for dynamic programming to be applicable:
Once these two conditions are met we can say that this divide and conquer problem may
be solved using dynamic programming approach.
Dynamic programming approach extends divide and conquer approach with two techniques
(memoization and tabulation) that both have a purpose of storing and re-using sub-problems
solutions that may drastically improve performance. For example naive recursive implemen-
tation of Fibonacci function has time complexity of O(2^n) where DP solution doing the
same with only O(n) time.
Memoization (top-down cache filling) refers to the technique of caching and reusing previ-
ously computed results. The memoized fib function would thus look like this:
memFib(n) {
if (mem[n] is undefined)
if (n < 2) result = n
else result = memFib(n-2) + memFib(n-1)
mem[n] = result
return mem[n]
}
Tabulation (bottom-up cache filling) is similar but focuses on filling the entries of the cache.
Computing the values in the cache is easiest done iteratively. The tabulation version of fib
would look like this:
882
Chapter 116. Dynamic Programming vs Divide-and-Conquer
Figure 116.1:
tabFib(n) {
mem[0] = 0
mem[1] = 1
for i = 2...n
mem[i] = mem[i-2] + mem[i-1]
return mem[n]
}
You may read more about memoization and tabulation comparison here.
The main idea you should grasp here is that because our divide and conquer problem has
overlapping sub-problems the caching of sub-problem solutions becomes possible and thus
memoization/tabulation step up onto the scene.
Since we’re now familiar with DP prerequisites and its methodologies we’re ready to put all
that was mentioned above into one picture.
Let’s go and try to solve some problems using DP and DC approaches to make this illustra-
tion more clear.
Binary search algorithm, also known as half-interval search, is a search algorithm that finds
883
Chapter 116. Dynamic Programming vs Divide-and-Conquer
the position of a target value within a sorted array. Binary search compares the target value
to the middle element of the array; if they are unequal, the half in which the target cannot
lie is eliminated and the search continues on the remaining half until the target value is
found. If the search ends with the remaining half being empty, the target is not in the array.
Example
Here is a visualization of the binary search algorithm where 4 is the target value.
Let’s draw the same logic but in form of decision tree.
You may clearly see here a divide and conquer principle of solving the problem. We’re
iteratively breaking the original array into sub-arrays and trying to find required element
in there.
Can we apply dynamic programming to it? No. It is because there are no overlapping sub-
problems. Every time we split the array into completely independent parts. And according
to divide and conquer prerequisites/restrictions the sub-problems must be overlapped some-
how.
Normally every time you draw a decision tree and it is actually a tree (and not a decision
graph) it would mean that you don’t have overlapping sub-problems and this is not dynamic
programming problem.
The Code
Here you may find complete source code of binary search function with test cases and
explanations.
884
Chapter 116. Dynamic Programming vs Divide-and-Conquer
Figure 116.2:
885
Chapter 116. Dynamic Programming vs Divide-and-Conquer
Figure 116.3:
886
Chapter 116. Dynamic Programming vs Divide-and-Conquer
Figure 116.4:
Normally when it comes to dynamic programming examples the Fibonacci number algorithm
is being taken by default. But let’s take a little bit more complex algorithm to have some
kind of variety that should help us to grasp the concept.
Minimum Edit Distance (or Levenshtein Distance) is a string metric for measuring the differ-
ence between two sequences. Informally, the Levenshtein distance between two words is the
minimum number of single-character edits (insertions, deletions or substitutions) required
to change one word into the other.
Example
For example, the Levenshtein distance between “kitten” and “sitting” is 3, since the following
three edits change one into the other, and there is no way to do it with fewer than three
edits:
Applications
This has a wide range of applications, for instance, spell checkers, correction systems for
optical character recognition, fuzzy string searching, and software to assist natural language
translation based on translation memory.
Mathematical Definition
Mathematically, the Levenshtein distance between two strings a, b (of length |a| and |b|
respectively) is given by function lev(|a|, |b|) where
Note that the first element in the minimum corresponds to deletion (from a to b), the second
to insertion and the third to match or mismatch, depending on whether the respective
symbols are the same.
Explanation
Ok, let’s try to figure out what that formula is talking about. Let’s take a simple example of
finding minimum edit distance between strings ME and MY. Intuitively you already know
that minimum edit distance here is 1 operation and this operation is “replace E with Y”. But
let’s try to formalize it in a form of the algorithm in order to be able to do more complex
examples like transforming Saturday into Sunday.
887
Chapter 116. Dynamic Programming vs Divide-and-Conquer
Figure 116.5: Simple example of finding minimum edit distance between ME and MY strings
To apply the formula to ME>MY transformation we need to know minimum edit distances
of ME>M, M>MY and M>M transformations in prior. Then we will need to pick the
minimum one and add +1 operation to transform last letters E?Y.
So we can already see here a recursive nature of the solution: minimum edit distance of
ME>MY transformation is being calculated based on three previously possible transforma-
tions. Thus we may say that this is divide and conquer algorithm.
To explain this further let’s draw the following matrix.
Cell (0, 1) contains red number 1. It means that we need 1 operation to transform M to
empty string: delete M. This is why this number is red.
Cell (0, 2) contains red number 2. It means that we need 2 operations to transform ME to
empty string: delete E, delete M.
Cell (1, 0) contains green number 1. It means that we need 1 operation to transform empty
string to M: insert M. This is why this number is green.
Cell (2, 0) contains green number 2. It means that we need 2 operations to transform empty
string to MY: insert Y, insert M.
Cell (1, 1) contains number 0. It means that it costs nothing to transform M to M.
Cell (1, 2) contains red number 1. It means that we need 1 operation to transform ME to
M: delete E.
And so on…
This looks easy for such small matrix as ours (it is only 3×3). But how we could calculate all
those numbers for bigger matrices (let’s say 9×7 one, for Saturday>Sunday transformation)?
The good news is that according to the formula you only need three adjacent cells (i-1, j),
(i-1, j-1), and (i, j-1) to calculate the number for current cell (i, j) . All we need to do is to
888
Chapter 116. Dynamic Programming vs Divide-and-Conquer
Figure 116.7: Decision graph for minimum edit distance with overlapping sub-problems
find the minimum of those three cells and then add +1 in case if we have different letters
in i-s row and j-s column
So once again you may clearly see the recursive nature of the problem.
Ok we’ve just found out that we’re dealing with divide and conquer problem here. But can
we apply dynamic programming approach to it? Does this problem satisfies our overlapping
sub-problems and optimal substructure restrictions? Yes. Let’s see it from decision graph.
First of all this is not a decision tree. It is a decision graph. You may see a number of
overlapping subproblems on the picture that are marked with red. Also there is no way to
reduce the number of operations and make it less then a minimum of those three adjacent
cells from the formula.
Also you may notice that each cell number in the matrix is being calculated based on
previous ones. Thus the tabulation technique (filling the cache in bottom-up direction) is
being applied here. You’ll see it in code example below.
Applying this principles further we may solve more complicated cases like with Saturday >
889
Chapter 116. Dynamic Programming vs Divide-and-Conquer
Sunday transformation.
The Code
Here you may find complete source code of minimum edit distance function with test cases
and explanations.
function levenshteinDistance(a, b) {
const distanceMatrix = Array(b.length + 1)
.fill(null)
.map(
() => Array(a.length + 1).fill(null)
);
890
Chapter 116. Dynamic Programming vs Divide-and-Conquer
distanceMatrix[j][i] = Math.min(
distanceMatrix[j][i - 1] + 1, // deletion
distanceMatrix[j - 1][i] + 1, // insertion
distanceMatrix[j - 1][i - 1] + indicator, // substitution
);
}
}
return distanceMatrix[b.length][a.length];
}
Conclusion
In this article we have compared two algorithmic approaches such as dynamic programming
and divide-and-conquer. We’ve found out that dynamic programing is based on divide and
conquer principle and may be applied only if the problem has overlapping sub-problems
and optimal substructure (like in Levenshtein distance case). Dynamic programming then
is using memoization or tabulation technique to store solutions of overlapping sub-problems
for later usage.
I hope this article hasn’t brought you more confusion but rather shed some light on these
two important algorithmic concepts! �
You may find more examples of divide and conquer and dynamic programming problems
with explanations, comments and test cases in JavaScript Algorithms and Data Structures
repository.
Happy coding!
Source
https://www.geeksforgeeks.org/dynamic-programming-vs-divide-and-conquer/
891
Chapter 117
Dynamic Programming |
Building Bridges
The values in the upper bank can be considered as the northern x-coordinates of the cities
and the values in the bottom bank can be considered as the corresponding southern x-
coordinates of the cities to which the northern x-coordinate city can be connected.
Examples:
Input : 6 4 2 1
2 3 6 5
Output : Maximum number of bridges = 2
892
Chapter 117. Dynamic Programming | Building Bridges
1 2 3 4 5 6
\ \
\ \ For the north-south pairs
\ \ (2, 6) and (1, 5)
\ \ the bridges can be built.
\ \ We can consider other pairs also,
\ \ but then only one bridge can be built
\ \ because more than one bridge built will
\ \ then cross each other.
\ \
1 2 3 4 5 6
Input : 8 1 4 3 5 2 6 7
1 2 3 4 5 6 7 8
Output : Maximum number of bridges = 2
Approach: It is a variation of LIS problem. The following are the steps to solve the
problem.
1. Sort the north-south pairs on the basis of increasing order of south x-coordinates.
2. If two south x-coordinates are same, then sort on the basis of increasing order of north
x-coordinates.
3. Now find the Longest Increasing Subsequence of the north x-coordinates.
4. One thing to note that in the increasing subsequence a value can be greater as well as
can be equal to its previous value.
We can also sort on the basis of north x-coordinates and find the LIS on the south x-
coordinates.
893
Chapter 117. Dynamic Programming | Building Bridges
{
if (a.south == b.south)
return a.north < b.north;
return a.south < b.south;
}
// function to find the maximum number
// of bridges that can be built
int maxBridges(struct CityPairs values[], int n)
{
int lis[n];
for (int i=0; i<n; i++)
lis[i] = 1;
sort(values, values+n, compare);
// logic of longest increasing subsequence
// applied on the northern coordinates
for (int i=1; i<n; i++)
for (int j=0; j<i; j++)
if (values[i].north >= values[j].north
&& lis[i] < 1 + lis[j])
lis[i] = 1 + lis[j];
int max = lis[0];
for (int i=1; i<n; i++)
if (max < lis[i])
max = lis[i];
// required number of bridges
// that can be built
return max;
}
// Driver program to test above
int main()
{
struct CityPairs values[] = {{6, 2}, {4, 3}, {2, 6}, {1, 5}};
int n = 4;
cout << "Maximum number of bridges = "
<< maxBridges(values, n);
return 0;
}
Output:
894
Chapter 117. Dynamic Programming | Building Bridges
Source
https://www.geeksforgeeks.org/dynamic-programming-building-bridges/
895
Chapter 118
Dynamic Programming |
High-effort vs. Low-effort Tasks
Problem
Optimal Substructure
To find the maximum amount of tasks done till i’th day, we need to compare 2 choices:
1. Go for high effort tasks on that day, then find the maximum amount of tasks done till
(i – 2) th day.
2. Go for low effort task on that day and find the maximum amount of tasks done till (i
– 1) th day.
896
Chapter 118. Dynamic Programming | High-effort vs. Low-effort Tasks Problem
Let high [1…n] be the input array for high effort task amount on i’th day and low [1…n] be
the input array for low effort task amount on ith day.
Let max_task (high [], low [], i) be the function that returns maximum amount of task done
till ith day, so it will return max(high[i] + max_task(high, low, (i – 2)), low [i] + max_task
(high, low, (i – 1)))
Therefore, the problem has optimal substructure property as the problem can be solved
using solutions to subproblems.
Overlapping Subproblems
Following is a simple recursive implementation of the High-effort vs. Low-effort task problem.
The implementation simply follows the recursive structure mentioned above. So, High-effort
vs. Low-effort Task Problem has both properties of a dynamic programming problem.
897
Chapter 118. Dynamic Programming | High-effort vs. Low-effort Tasks Problem
Output :
20
It should be noted that the above function computes the same subproblems again and again.
Therefore, this problem has Overlapping Subproblems Property. So the High-effort vs. Low-
effort Task Problem has both the properties of a dynamic programming problem.
Dynamic Programming Solution
898
Chapter 118. Dynamic Programming | High-effort vs. Low-effort Tasks Problem
Output:
20
Source
https://www.geeksforgeeks.org/dynamic-programming-high-effort-vs-low-effort-tasks-problem/
899
Chapter 119
Dynamic Programming |
Wildcard Pattern Matching |
Linear Time and Constant
Space
Dynamic Programming | Wildcard Pattern Matching | Linear Time and Constant Space -
GeeksforGeeks
Given a text and a wildcard pattern, find if wildcard pattern is matched with text. The
matching should cover the entire text (not partial text).
The wildcard pattern can include the characters ‘?’ and ‘*’
‘?’ – matches any single character
‘*’ – Matches any sequence of characters (including the empty sequence)
Prerequisite : Dynamic Programming | Wildcard Pattern Matching
Examples:
Text = "baaabab",
Pattern = “*****ba*****ab", output : true
Pattern = "baaa?ab", output : true
Pattern = "ba*a?", output : true
Pattern = "a*ab", output : false
900
Chapter 119. Dynamic Programming | Wildcard Pattern Matching | Linear Time and
Constant Space
Each occurrence of ‘?’ character in wildcard pattern can be replaced with any other character
and each occurrence of ‘*’ with a sequence of characters such that the wildcard pattern
becomes identical to the input string after replacement.
We have discussed a solution here which has O(m x n) time and O(m x n) space complexity.
For applying the optimization, we will at first note the BASE CASE which involves :
If the length of the pattern is zero then answer will be true only if the length of the text
with which we have to match the pattern is also zero.
ALGORITHM | (STEP BY STEP)
Step – (1) : Let i be the marker to point at the current character of the text.
Let j be the marker to point at the current character of the pattern.
Let index_txt be the marker to point at the character of text on which we encounter ‘*’ in
pattern.
Let index_pat be the marker to point at the position of ‘*’ in the pattern.
NOTE : WE WILL TRAVERSE THE GIVEN STRING AND PATTERN US-
ING A WHILE LOOP
Step – (2) : At any instant if we observe that txt[i] == pat[j], then we increment both i and
j as no operation needs to be performed in this case.
901
Chapter 119. Dynamic Programming | Wildcard Pattern Matching | Linear Time and
Constant Space
Step – (3) : If we encounter pat[j] == ‘?’, then it resembles the case mentioned in step –
(2) as ‘?’ has the property to match with any single character.
Step – (4) : If we encounter pat[j] == ‘*’, then we update the value of index_txt and
index_pat as ‘*’ has the property to match any sequence of characters (including the empty
sequence) and we will increment the value of j to compare next character of pattern with
the current character of the text.(As character represented by i has not been answered yet).
Step – (5) : Now if txt[i] == pat[j], and we have encountered a ‘*’ before, then it means
that ‘*’ included the empty sequence, else if txt[i] != pat[j], a character needs to be provided
by ‘*’ so that current character matching takes place, then i needs to be incremented as it
is answered now but the character represented by j still needs to be answered, therefore, j =
index_pat + 1, i = index_txt + 1 (as ‘*’ can capture other characters as well), index_txt++
(as current character in text is matched).
Step – (6) : If step – (5) is not valid, that means txt[i] != pat[j], also we have not encountered
a ‘*’ that means it is not possible for the pattern to match the string. (return false).
Step – (7) : Check whether j reached its final value or not, then return the final answer.
Let us see the above algorithm in action, then we will move to the coding section
:
text = “baaabab”
pattern = “*****ba*****ab”
NOW APPLYING THE ALGORITHM
Step – (1) : i = 0 (i –> ‘b’)
j = 0 (j –> ‘*’)
index_txt = -1
index_pat = -1
NOTE : LOOP WILL RUN TILL i REACHES ITS FINAL
VALUE OR THE ANSWER BECOMES FALSE MIDWAY.
FIRST COMPARISON :-
As we see here that pat[j] == ‘*’, therefore directly jumping on to step – (4).
Step – (4) : index_txt = i (index_txt –> ‘b’)
index_pat = j (index_pat –> ‘*’)
j++ (j –> ‘*’)
After four more comparisons : i = 0 (i –> ‘b’)
j = 5 (j –> ‘b’)
index_txt = 0 (index_txt –> ‘b’)
index_pat = 4 (index_pat –> ‘*’)
SIXTH COMPARISON :-
As we see here that txt[i] == pat[j], but we already encountered ‘*’ therefore using step –
(5).
Step – (5) : i = 1 (i –> ‘a’)
j = 6 (j –> ‘a’)
index_txt = 0 (index_txt –> ‘b’)
index_pat = 4 (index_pat –> ‘*’)
902
Chapter 119. Dynamic Programming | Wildcard Pattern Matching | Linear Time and
Constant Space
SEVENTH COMPARISON :-
Step – (5) : i = 2 (i –> ‘a’)
j = 7 (j –> ‘*’)
index_txt = 0 (index_txt –> ‘b’)
index_pat = 4 (index_pat –> ‘*’)
EIGTH COMPARISON :-
Step – (4) : i = 2 (i –> ‘a’)
j = 8 (j –> ‘*’)
index_txt = 2 (index_txt –> ‘a’)
index_pat = 7 (index_pat –> ‘*’)
After four more comparisons : i = 2 (i –> ‘a’)
j = 12 (j –> ‘a’)
index_txt = 2 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
THIRTEENTH COMPARISON :-
Step – (5) : i = 3 (i –> ‘a’)
j = 13 (j –> ‘b’)
index_txt = 2 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
FOURTEENTH COMPARISON :-
Step – (5) : i = 3 (i –> ‘a’)
j = 12 (j –> ‘a’)
index_txt = 3 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
FIFTEENTH COMPARISON :-
Step – (5) : i = 4 (i –> ‘b’)
j = 13 (j –> ‘b’)
index_txt = 3 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
SIXTEENTH COMPARISON :-
Step – (5) : i = 5 (i –> ‘a’)
j = 14 (j –> end)
index_txt = 3 (index_txt –> ‘a’)
index_pat = 11 (index_pat –> ‘*’)
SEVENTEENTH COMPARISON :-
Step – (5) : i = 4 (i –> ‘b’)
j = 12 (j –> ‘a’)
index_txt = 4 (index_txt –> ‘b’)
index_pat = 11 (index_pat –> ‘*’)
EIGHTEENTH COMPARISON :-
903
Chapter 119. Dynamic Programming | Wildcard Pattern Matching | Linear Time and
Constant Space
904
Chapter 119. Dynamic Programming | Wildcard Pattern Matching | Linear Time and
Constant Space
j++;
}
// For step - (3)
else if (j < m && pat[j] == '?') {
i++;
j++;
}
// For step - (4)
else if (j < m && pat[j] == '*') {
index_txt = i;
index_pat = j;
j++;
}
// For step - (5)
else if (index_pat != -1) {
j = index_pat + 1;
i = index_txt + 1;
index_txt++;
}
// For step - (6)
else {
return false;
}
}
// For step - (7)
while (j < m && pat[j] == '*') {
j++;
}
// Final Check
if (j == m) {
return true;
}
return false;
}
// Driver code
int main()
{
char str[] = "baaabab";
char pattern[] = "*****ba*****ab";
// char pattern[] = "ba*****ab";
905
Chapter 119. Dynamic Programming | Wildcard Pattern Matching | Linear Time and
Constant Space
Output:
Yes
No
Source
https://www.geeksforgeeks.org/dynamic-programming-wildcard-pattern-matching-linear-time-constant-space/
906
Chapter 120
• Insert
• Remove
• Replace
<div
What are the subproblems in this case? The idea is to process all characters one by
one staring from either from left or right sides of both strings. Let us traverse from right
907
Chapter 120. Edit Distance | DP using Memoization
corner, there are two possibilities for every pair of character being traversed. The following
are the conditions:
1. If last characters of two strings are same, nothing much to do. Ignore last characters
and get count for remaining strings. So we recur for lengths m-1 and n-1.
2. Else (If last characters are not same), we consider all operations on ‘str1’, consider all
three operations on last character of first string, recursively compute minimum cost
for all three operations and take minimum of three values.
• Insert: Recur for m and n-1
• Remove: Recur for m-1 and n
• Replace: Recur for m-1 and n-1
908
Chapter 120. Edit Distance | DP using Memoization
// compute minimum cost for all three operations and take
// minimum of three values.
return 1 + min(editDist(str1, str2, m, n - 1), // Insert
editDist(str1, str2, m - 1, n), // Remove
editDist(str1, str2, m - 1, n - 1) // Replace
);
}
// Driver program
int main()
{
// your code goes here
string str1 = "sunday";
string str2 = "saturday";
cout << editDist(str1, str2, str1.length(), str2.length());
return 0;
}
Java
909
Chapter 120. Edit Distance | DP using Memoization
// much to do. Ignore last characters and get count for
// remaining strings.
if (str1.charAt(m - 1) == str2.charAt(n - 1))
return editDist(str1, str2, m - 1, n - 1);
// If last characters are not same, consider all three
// operations on last character of first string, recursively
// compute minimum cost for all three operations and take
// minimum of three values.
return 1 + min(editDist(str1, str2, m, n - 1), // Insert
editDist(str1, str2, m - 1, n), // Remove
editDist(str1, str2, m - 1, n - 1) // Replace
);
}
public static void main(String args[])
{
String str1 = "sunday";
String str2 = "saturday";
System.out.println(editDist(str1, str2, str1.length(), str2.length()));
}
}
Python
910
Chapter 120. Edit Distance | DP using Memoization
# compute minimum cost for all three operations and take
# minimum of three values.
return 1 + min(editDistance(str1, str2, m, n-1), # Insert
editDistance(str1, str2, m-1, n), # Remove
editDistance(str1, str2, m-1, n-1) # Replace
)
# Driver program to test the above function
str1 = "sunday"
str2 = "saturday"
print editDistance(str1, str2, len(str1), len(str2))
C#
911
Chapter 120. Edit Distance | DP using Memoization
Output:
The time complexity of above solution is O(3^n) which is exponential. The worst case
happens when none of characters of two strings match. Below is a recursive call diagram
for worst case.
We can see that many subproblems are solved, again and again, for example, eD(2, 2) is
called three times. Since same suproblems are called again, this problem has Overlapping
912
Chapter 120. Edit Distance | DP using Memoization
Subprolems property. So Edit Distance problem has both properties (see thisand this) of a
dynamic programming problem. Like other typical Dynamic Programming(DP) problems,
recomputations of same subproblems can be avoided by constructing a temporary array that
stores results of subproblems. The bottom-up approach can be found here.
The problem can also be solved using top-down Dynamic Programming and using mem-
oization. In the recursive code, memoization can be used to avoid overlapping problems.
There are several repetitive calls which can be computed in O(1) if the value is stored when
called for the first time. On observing the recursive code, it is seen that a maximum of two
parameters is changing their value on every recursive call. There will be cases when the
same recursive call has been called previously. Since two parameters are not constant, a
2-D array can be used to avoid repetitive calls. Hence the return value is stored in some
2-D array. Below are the steps:
913
Chapter 120. Edit Distance | DP using Memoization
914
Chapter 120. Edit Distance | DP using Memoization
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/edit-distance-dp-using-memoization/
915
Chapter 121
One solution is to simply modify Edit Distance Solution by making two recursive call instead
of three. An interesting solution is based on LCS.
1) Find LCS of two strings. Let length of LCS be x.
2) Let length of first string be m and length of second string be n. Our result is (m – x) +
(n – x). We basically need to do (m – x) delete operations and (n – x) insert operations.
916
Chapter 121. Edit distance and LCS (Longest Common Subsequence)
Output:
Source
https://www.geeksforgeeks.org/edit-distance-and-lcs-longest-common-subsequence/
917
Chapter 122
918
Chapter 122. Efficient program to print all prime factors of a given number
Java
919
Chapter 122. Efficient program to print all prime factors of a given number
while (n%i == 0)
{
System.out.print(i + " ");
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
System.out.print(n);
}
public static void main (String[] args)
{
int n = 315;
primeFactors(n);
}
}
Python
920
Chapter 122. Efficient program to print all prime factors of a given number
# Driver Program to test above function
n = 315
primeFactors(n)
# This code is contributed by Harshit Agrawal
C#
921
Chapter 122. Efficient program to print all prime factors of a given number
PHP
<?php
// PHP Efficient program to print all
// prime factors of a given number
// function to print all prime
// factors of a given number n
function primeFactors($n)
{
// Print the number of
// 2s that divide n
while($n % 2 == 0)
{
echo 2," ";
$n = $n / 2;
}
// n must be odd at this
// point. So we can skip
// one element (Note i = i +2)
for ($i = 3; $i <= sqrt($n);
$i = $i + 2)
{
// While i divides n,
// print i and divide n
while ($n % $i == 0)
{
echo $i," ";
$n = $n / $i;
}
}
// This condition is to
// handle the case when n
922
Chapter 122. Efficient program to print all prime factors of a given number
Output:
3 3 5 7
923
Chapter 122. Efficient program to print all prime factors of a given number
Source
https://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/
924
Chapter 123
Entringer Number
Input : n = 4, k = 2
Output : 4
Input : n = 4, k = 3
Output : 5
Below is program to find Entringer Number E(n, k). The program is based on above simple
recursive formula.
C++
925
Chapter 123. Entringer Number
Java
926
Chapter 123. Entringer Number
zigzag(n - 1, n - k);
}
/* Driver program to test above function */
public static void main(String[] args)
{
int n = 4, k = 3;
System.out.println(zigzag(n, k));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
C#
927
Chapter 123. Entringer Number
PHP
<?php
// PHP Program to find
// Entringer Number E(n, k)
// Return Entringer Number E(n, k)
function zigzag($n, $k)
{
// Base Case
if ($n == 0 and $k == 0)
return 1;
// Base Case
if ($k == 0)
return 0;
// Recursive step
return zigzag($n, $k - 1) +
zigzag($n - 1,$n - $k);
}
928
Chapter 123. Entringer Number
// Driven Code
$n = 4; $k = 3;
echo zigzag($n, $k) ;
// This code is contributed by anuj_67.
?>
Output :
C++
929
Chapter 123. Entringer Number
Java
Python3
930
Chapter 123. Entringer Number
# Base cases
dp[0][0] = 1
for i in range(1, n+1):
dp[i][0] = 0
# Finding dp[i][j]
for i in range(1, n+1):
for j in range(1, k+1):
dp[i][j] = (dp[i][j - 1]
+ dp[i - 1][i - j])
return dp[n][k]
# Driven Program
n = 4
k = 3
print(zigzag(n, k))
# This code is contributed by
# Prasad Kshirsagar
C#
931
Chapter 123. Entringer Number
/* Driver program to test above function */
public static void Main()
{
int n = 4, k = 3;
Console.WriteLine(zigzag(n, k));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to find
// Entringer Number E(n, k)
// Return Entringer Number E(n, k)
function zigzag($n, $k)
{
$dp = array(array());
// Base cases
$dp[0][0] = 1;
for ($i = 1; $i <= $n; $i++)
$dp[$i][0] = 0;
// Finding dp[i][j]
for ($i = 1; $i <= $n; $i++)
{
for ($j = 1; $j <= $i; $j++)
$dp[$i][$j] = $dp[$i][$j - 1] +
$dp[$i - 1][$i - $j];
}
return $dp[$n][$k];
}
// Driven Code
$n = 4; $k = 3;
echo zigzag($n, $k);
// This code is contributed by anuj_67.
?>
Output :
932
Chapter 123. Entringer Number
Source
https://www.geeksforgeeks.org/entringer-number/
933
Chapter 124
Eulerian Number
Examples :
Input : n = 3, m = 1
Output : 4
Please see above diagram (There
are 4 permutations where 1 no. is
greater.
Input : n = 4, m = 1
Output : 11
Eulerian Numbers are the coefficients of the Eulerian polynomials described below.
934
Chapter 124. Eulerian Number
Example:
Suppose, n = 3 and m = 1.
Therefore,
A(3, 1)
= (3 – 1) * A(2, 0) + (1 + 1) * A(2, 1)
= 2 * A(2, 0) + 2 * A(2, 1)
= 2 * 1 + 2 * ( (2 – 1) * A(1, 0) + (1 + 1) * A(1, 1))
= 2 + 2 * (1 * 1 + 2 * ((1 – 1) * A(0, 0) + (1 + 1) * A(0, 1))
= 2 + 2 * (1 + 2 * (0 * 1 + 2 * 0)
= 2 + 2 * (1 + 2 * 0)
=2+2*1
=2+2
=4
We can verify this with example shown above.
Below is the implementation of finding A(n, m):
C++
935
Chapter 124. Eulerian Number
#include <bits/stdc++.h>
using namespace std;
// Return euleriannumber A(n, m)
int eulerian(int n, int m)
{
if (m >= n || n == 0)
return 0;
if (m == 0)
return 1;
return (n - m) * eulerian(n - 1, m - 1) +
(m + 1) * eulerian(n - 1, m);
}
// Driven Program
int main()
{
int n = 3, m = 1;
cout << eulerian(n, m) << endl;
return 0;
}
Java
936
Chapter 124. Eulerian Number
System.out.print( eulerian(n, m) );
}
}
// This code is contributed by rishabh_jain
Python3
C#
937
Chapter 124. Eulerian Number
// driver code
public static void Main()
{
int n = 3, m = 1;
Console.WriteLine(eulerian(n, m));
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP Program to find
// Eulerian number A(n, m)
// Return euleriannumber A(n, m)
function eulerian($n, $m)
{
if ($m >= $n || $n == 0)
return 0;
if ($m == 0)
return 1;
return ($n - $m) * eulerian($n - 1, $m - 1) +
($m + 1) * eulerian($n - 1, $m);
}
// Driven Code
$n = 3; $m = 1;
echo eulerian($n, $m);
// This code is contributed by anuj_67.
?>
Output :
C++
938
Chapter 124. Eulerian Number
Java
939
Chapter 124. Eulerian Number
import java.util.*;
class Eulerian
{
// Return euleriannumber A(n, m)
public static int eulerian(int n, int m)
{
int[][] dp = new int[n+1][m+1];
// For each row from 1 to n
for (int i = 1; i <= n; i++) {
// For each column from 0 to m
for (int j = 0; j <= m; j++) {
// If i is greater than j
if (i > j) {
// If j is 0, then make
// that state as 1.
if (j == 0)
dp[i][j] = 1;
// basic recurrence relation.
else
dp[i][j] = ((i - j) *
dp[i - 1][j - 1]) +
((j + 1) * dp[i - 1][j]);
}
}
}
return dp[n][m];
}
// driver code
public static void main(String[] args)
{
int n = 3, m = 1;
System.out.print( eulerian(n, m) );
}
}
// This code is contributed by rishabh_jain
Python3
940
Chapter 124. Eulerian Number
# number A(n, m)
# Return euleriannumber A(n, m)
def eulerian(n, m):
dp = [[0 for x in range(m+1)]
for y in range(n+1)]
# For each row from 1 to n
for i in range(1, n+1):
# For each column from 0 to m
for j in range(0, m+1):
# If i is greater than j
if (i > j):
# If j is 0, then make that
# state as 1.
if (j == 0):
dp[i][j] = 1
# basic recurrence relation.
else :
dp[i][j] = (((i - j) *
dp[i - 1][j - 1]) +
((j + 1) * dp[i - 1][j]))
return dp[n][m]
# Driven Program
n = 3
m = 1
print(eulerian(n, m))
# This code is contributed by Prasad Kshirsagar
C#
941
Chapter 124. Eulerian Number
Output :
Source
https://www.geeksforgeeks.org/eulerian-number/
942
Chapter 125
Input:
Number of Jobs n = 4
Job Details {Start Time, Finish Time, Profit}
Job 1: {1, 2, 50}
Job 2: {3, 5, 20}
Job 3: {6, 19, 100}
Job 4: {2, 100, 200}
Output:
Jobs involved in maximum profit are
Job 1: {1, 2, 50}
Job 4: {2, 100, 200}
In previous post, we have discussed about Weighted Job Scheduling problem. However, the
post only covered code related to finding maximum profit. In this post, we will also print
the jobs invloved in maximum profit.
943
Chapter 125. Find Jobs involved in Weighted Job Scheduling
Let arr[0..n-1] be the input array of Jobs. We define an array DP[] such that DP[i] stores
Jobs involved to achieve maximum profit of array arr[0..i]. i.e. DP[i] stores solution to
subproblem arr[0..i]. The rest of algorithm remains same as discussed in previous post.
Below is its C++ implementation –
944
Chapter 125. Find Jobs involved in Weighted Job Scheduling
{
if (jobs[mid + 1].finish <= jobs[index].start)
lo = mid + 1;
else
return mid;
}
else
hi = mid - 1;
}
return -1;
}
// The main function that finds the subset of jobs
// associated with maximum profit such that no two
// jobs in the subset overlap.
int findMaxProfit(Job arr[], int n)
{
// Sort jobs according to finish time
sort(arr, arr + n, jobComparator);
// Create an array to store solutions of subproblems.
// DP[i] stores the Jobs involved and their total profit
// till arr[i] (including arr[i])
weightedJob DP[n];
// initialize DP[0] to arr[0]
DP[0].value = arr[0].profit;
DP[0].job.push_back(arr[0]);
// Fill entries in DP[] using recursive property
for (int i = 1; i < n; i++)
{
// Find profit including the current job
int inclProf = arr[i].profit;
int l = latestNonConflict(arr, i);
if (l != - 1)
inclProf += DP[l].value;
// Store maximum of including and excluding
if (inclProf > DP[i - 1].value)
{
DP[i].value = inclProf;
// including previous jobs and current job
DP[i].job = DP[l].job;
DP[i].job.push_back(arr[i]);
945
Chapter 125. Find Jobs involved in Weighted Job Scheduling
}
else
// excluding the current job
DP[i] = DP[i - 1];
}
// DP[n - 1] stores the result
cout << "Optimal Jobs for maximum profits are\n" ;
for (int i=0; i<DP[n-1].job.size(); i++)
{
Job j = DP[n-1].job[i];
cout << "(" << j.start << ", " << j.finish
<< ", " << j.profit << ")" << endl;
}
cout << "\nTotal Optimal profit is " << DP[n - 1].value;
}
// Driver program
int main()
{
Job arr[] = {{3, 5, 20}, {1, 2, 50}, {6, 19, 100},
{2, 100, 200} };
int n = sizeof(arr)/sizeof(arr[0]);
findMaxProfit(arr, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-jobs-involved-in-weighted-job-scheduling/
946
Chapter 126
Find Maximum dot product of two arrays with insertion of 0’s - GeeksforGeeks
Given two arrays of positive integers of size m and n where m > n. We need to maximize
the dot product by inserting zeros in the second array but we cannot disturb the order of
elements.
Examples:
1. We multiply A[i] and B[j] and add to product (We include A[i]).
2. We exclude A[i] from product (In other words, we insert 0 at current position in B[])
947
Chapter 126. Find Maximum dot product of two arrays with insertion of 0’s
C++
948
Chapter 126. Find Maximum dot product of two arrays with insertion of 0’s
Java
949
Chapter 126. Find Maximum dot product of two arrays with insertion of 0’s
Output:
107
Source
https://www.geeksforgeeks.org/find-maximum-dot-product-two-arrays-insertion-0s/
950
Chapter 127
Find all combinations of k-bit numbers with n bits set where 1 <= n <= k in sorted order
- GeeksforGeeks
Given a number k, find all the possible combinations of k-bit numbers with n-bits set where
1 <= n <= k. The solution should print all numbers with one set bit first, followed by
numbers with two bits set,.. up to the numbers whose all k-bits are set. If two numbers
have the same number of set bits, then smaller number should come first.
Examples:
Input: K = 3
Output:
001 010 100
011 101 110
111
Input: K = 4
Output:
0001 0010 0100 1000
0011 0101 0110 1001 1010 1100
0111 1011 1101 1110
1111
Input: K = 5
Output:
00001 00010 00100 01000 10000
00011 00101 00110 01001 01010 01100 10001 10010 10100 11000
951
Chapter 127. Find all combinations of k-bit numbers with n bits set where 1 <= n <= k
in sorted order
00111 01011 01101 01110 10011 10101 10110 11001 11010 11100
01111 10111 11011 11101 11110
11111
We need to find all the possible combinations of k-bit numbers with n set bits where 1 <= n
<= k. If we carefully analyze, we see that problem can further be divided into sub-problems.
We can find all combinations of length k with n ones by prefixing 0 to all combinations of
length k-1 with n ones and 1 to all combinations of length k-1 with n-1 ones. We can use
Dynamic Programming to save solutions of sub-problems.
Below is C++ implementation of above idea –
952
Chapter 127. Find all combinations of k-bit numbers with n bits set where 1 <= n <= k
in sorted order
// prefix 1 to all combinations of length len-1
// with n-1 ones
for (string str : DP[len - 1][n - 1])
DP[len][n].push_back("1" + str);
}
}
// print all k-bit binary strings with
// n-bit set
for (int n = 1; n <= k; n++)
{
for (string str : DP[k][n])
cout << str << " ";
cout << endl;
}
}
// Driver code
int main()
{
int k = 5;
findBitCombinations(k);
return 0;
}
Output:
00000
00001 00010 00100 01000 10000
00011 00101 00110 01001 01010 01100 10001 10010 10100 11000
00111 01011 01101 01110 10011 10101 10110 11001 11010 11100
01111 10111 11011 11101 11110
11111
Source
https://www.geeksforgeeks.org/find-combinations-k-bit-numbers-n-bits-set-1-n-k-sorted-order/
953
Chapter 128
954
Chapter 128. Find all distinct palindromic sub-strings of a given string
955
Chapter 128. Find all distinct palindromic sub-strings of a given string
Java
956
Chapter 128. Find all distinct palindromic sub-strings of a given string
957
Chapter 128. Find all distinct palindromic sub-strings of a given string
k++;
}
rp = Math.max(rp - k,0);
i += k;
}
}
// remove 'guards'
s = s.substring(1, s.length()-1);
// Put all obtained palindromes in a hash map to
// find only distinct palindromess
m.put(s.substring(0,1), 1);
for (int i = 1; i < n; i++)
{
for (int j = 0; j <= 1; j++)
for (int rp = R[j][i]; rp > 0; rp--)
m.put(s.substring(i - rp - 1, i - rp - 1
+ 2 * rp + j), 1);
m.put(s.substring(i, i + 1), 1);
}
// printing all distinct palindromes from
// hash map
System.out.println("Below are " + (m.size())
+ " palindrome sub-strings");
for (Map.Entry<String, Integer> ii:m.entrySet())
System.out.println(ii.getKey());
}
// Driver program
public static void main(String args[])
{
palindromeSubStrs("abaaa");
}
}
// This code is contributed by Sumit Ghosh
Python
958
Chapter 128. Find all distinct palindromic sub-strings of a given string
# table for storing results (2 rows for odd-
# and even-length palindromes
R = [[0 for x in xrange(n+1)] for x in xrange(2)]
# Find all sub-string palindromes from the given input
# string insert 'guards' to iterate easily over s
s = "@" + s + "#"
for j in xrange(2):
rp = 0 # length of 'palindrome radius'
R[j][0] = 0
i = 1
while i <= n:
# Attempt to expand palindrome centered at i
while s[i - rp - 1] == s[i + j + rp]:
rp += 1 # Incrementing the length of palindromic
# radius as and when we find valid palindrome
# Assigning the found palindromic length to odd/even
# length array
R[j][i] = rp
k = 1
while (R[j][i - k] != rp - k) and (k < rp):
R[j][i+k] = min(R[j][i-k], rp - k)
k += 1
rp = max(rp - k, 0)
i += k
# remove guards
s = s[1:len(s)-1]
# Put all obtained palindromes in a hash map to
# find only distinct palindrome
m[s[0]] = 1
for i in xrange(1,n):
for j in xrange(2):
for rp in xrange(R[j][i],0,-1):
m[s[i - rp - 1 : i - rp - 1 + 2 * rp + j]] = 1
m[s[i]] = 1
# printing all distinct palindromes from hash map
print "Below are " + str(len(m)) + " pali sub-strings"
for i in m:
print i
959
Chapter 128. Find all distinct palindromic sub-strings of a given string
# Driver program
palindromeSubStrs("abaaa")
# This code is contributed by BHAVYA JAIN and ROHIT SIKKA
Output:
Similar Problem:
Count All Palindrome Sub-Strings in a String
This article is contributed by Vignesh Narayanan and Sowmya Sampath. Please write
comments if you find anything incorrect, or you want to share more information about the
topic discussed above.
Improved By : utkarshver
Source
https://www.geeksforgeeks.org/find-number-distinct-palindromic-sub-strings-given-string/
960
Chapter 129
The naive solution for this problem is to generate all the subsets, store their sums in a
hash set and finally print all keys from hash set.
C++
961
Chapter 129. Find all distinct subset (or subsequence) sums of an array
Java
962
Chapter 129. Find all distinct subset (or subsequence) sums of an array
963
Chapter 129. Find all distinct subset (or subsequence) sums of an array
}
// This code is contributed by Gitanjali.
Output:
0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20
C++
964
Chapter 129. Find all distinct subset (or subsequence) sums of an array
Java
965
Chapter 129. Find all distinct subset (or subsequence) sums of an array
C#
966
Chapter 129. Find all distinct subset (or subsequence) sums of an array
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// dp[i][j] would be true if arr[0..i-1]
// has a subset with sum equal to j.
bool [,]dp = new bool[n + 1,sum + 1];
// There is always a subset with 0 sum
for (int i = 0; i <= n; i++)
dp[i,0] = true;
// Fill dp[][] in bottom up manner
for (int i = 1; i <= n; i++)
{
dp[i,arr[i - 1]] = true;
for (int j = 1; j <= sum; j++)
{
// Sums that were achievable
// without current array element
if (dp[i - 1,j] == true)
{
dp[i,j] = true;
dp[i,j + arr[i - 1]] = true;
}
}
}
// Print last row elements
for (int j = 0; j <= sum; j++)
if (dp[n,j] == true)
Console.Write(j + " ");
}
// Driver code
public static void Main()
{
int []arr = { 2, 3, 4, 5, 6 };
int n = arr.Length;
printDistSum(arr, n);
}
}
// This code is contributed by nitin mittal.
Output:
0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20
967
Chapter 129. Find all distinct subset (or subsequence) sums of an array
Time complexity of the above approach is O(n*sum) where n is the size of the array and
sum is the sum of all the integers in the array.
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/find-distinct-subset-subsequence-sums-array/
968
Chapter 130
Find all distinct subset (or subsequence) sums of an array | Set-2 - GeeksforGeeks
Given an array of N positive integers write an efficient function to find the sum of all those
integers which can be expressed as the sum of at least one subset of the given array i.e.
calculate total sum of each subset whose sum is distinct using only O(sum) extra space.
Examples:
A post using O(N*sum) and O(N*sum) space has been discussed in this post.
In this post, an approach using O(sum) space has been discussed. Create a single dp array
of O(sum) space and mark the dp[a[0]] as true and the rest as false. Iterate for all the array
elements in the array and then iterate from 1 to sum for each element in the array and
mark all the dp[j] with true that satisfies the condition (arr[i] == j || dp[j] || dp[(j –
arr[i])]). At the end print all the index that are marked true. Since arr[i]==j denotes the
subset with single element and dp[(j – arr[i])] denotes the subset with element j-arr[i].
Below is the implementation of the above approach.
969
Chapter 130. Find all distinct subset (or subsequence) sums of an array | Set-2
970
Chapter 130. Find all distinct subset (or subsequence) sums of an array | Set-2
Output:
0 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 21
Source
https://www.geeksforgeeks.org/find-all-distinct-subset-or-subsequence-sums-of-an-array-set-2/
971
Chapter 131
If we carefully analyze the problem, the task is to transform the given string into its reverse
by removing at most K characters from it. The problem is basically a variation of Edit
Distance. We can modify the Edit Distance problem to consider given string and its reverse
as input and only operation allowed is deletion. Since given string is compared with its
reverse, we will do at most N deletions from first string and N deletions from second string
to make them equal. Therefore, for a string to be k-palindrome, 2*N <= 2*K should hold
972
Chapter 131. Find if string is K-Palindrome or not | Set 1
true. Below are the detailed steps of algorithm - Process all characters one by one staring
from either from left or right sides of both strings. Let us traverse from the right corner,
there are two possibilities for every pair of character being traversed.
1. If last characters of two strings are same, we ignore last characters and get count for
remaining strings. So we recur for lengths m-1 and n-1 where m is length of str1 and
n is length of str2.
2. If last characters are not same, we consider remove operation on last character of first
string and last character of second string, recursively compute minimum cost for the
operations and take minimum of two values.
• Remove last char from str1: Recur for m-1 and n.
• Remove last char from str2: Recur for m and n-1.
C++
973
Chapter 131. Find if string is K-Palindrome or not | Set 1
Python3
974
Chapter 131. Find if string is K-Palindrome or not | Set 1
Output :
Yes
The time complexity of above solution is exponential. In worst case, we may end up doing
O(2n ) operations. The worst case happens string contains all distinct characters.
This problem has both properties (see this and this) of a dynamic programming problem.
Like other typical Dynamic Programming(DP) problems, re-computations of same subprob-
lems can be avoided by constructing a temporary array that stores results of subproblems
.
Below is Bottom-up implementation of above recursive approach :
C++
975
Chapter 131. Find if string is K-Palindrome or not | Set 1
976
Chapter 131. Find if string is K-Palindrome or not | Set 1
Python3
977
Chapter 131. Find if string is K-Palindrome or not | Set 1
Output :
Yes
Time complexity of above solution is O(m x n). We can improve time complexity by making
use of the fact that only k deletions are allowed. Auxiliary space used is O(m x n).
Find if string is K-Palindrome or not | Set 2 (Using LCS)
Source
https://www.geeksforgeeks.org/find-if-string-is-k-palindrome-or-not/
978
Chapter 132
We have discussed a DP solution in previous post where we saw that the problem is basically
a variation of Edit Distance problem. In this post, another interesting DP solution is
discussed.
The idea is to find the longest palindromic subsequence of the given string. If the difference
between longest palindromic subsequence and the original string is less than equal to k, then
the string is k-palindrome else it is not k-palindrome.
979
Chapter 132. Find if string is K-Palindrome or not | Set 2
For example, longest palindromic subsequence of string abcdeca is acdca(or aceca). The
characters which do not contribute to longest palindromic subsequence of the string should
be removed in order to make the string palindrome. So on removing b and d (or e) from
abcdeca, string will transform into a palindrome.
Longest palindromic subsequence of a string can easily be found using LCS. Following is the
two step solution for finding longest palindromic subsequence that uses LCS.
1. Reverse the given sequence and store the reverse in another array say rev[0..n-1]
2. LCS of the given sequence and rev[] will be the longest palindromic sequence.
980
Chapter 132. Find if string is K-Palindrome or not | Set 2
// Find reverse of string
string revStr = str;
reverse(revStr.begin(), revStr.end());
// find longest palindromic subsequence of
// given string
int lps = lcs(str, revStr, n, n);
// If the difference between longest palindromic
// subsequence and the original string is less
// than equal to k, then the string is k-palindrome
return (n - lps <= k);
}
// Driver program
int main()
{
string str = "abcdeca";
int k = 2;
isKPal(str, k) ? cout << "Yes" : cout << "No";
return 0;
}
Python3
981
Chapter 132. Find if string is K-Palindrome or not | Set 2
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
# L[m][n] contains length
# of LCS for X and Y
return L[m][n]
# find if given string is
# K-Palindrome or not
def isKPal(string, k):
n = len(string)
# Find reverse of string
revStr = string[::-1]
# find longest palindromic
# subsequence of
# given string
lps = lcs(string, revStr, n, n)
# If the difference between
# longest palindromic
# subsequence and the original
# string is less
# than equal to k, then
# the string is k-palindrome
return (n - lps <= k)
# Driver program
string = "abcdeca"
k = 2
print("Yes" if isKPal(string, k) else "No")
# This code is contributed
# by Ansu Kumari.
Output:
Yes
982
Chapter 132. Find if string is K-Palindrome or not | Set 2
Source
https://www.geeksforgeeks.org/find-if-string-is-k-palindrome-or-not-set-2/
983
Chapter 133
Find length of longest subsequence of one string which is substring of another string -
GeeksforGeeks
Given two string X and Y. The task is to find the length of longest subsequence of string
X which is substring in sequence Y.
Examples:
984
Chapter 133. Find length of longest subsequence of one string which is substring of
another string
for (i = 1 to m)
for (j = 1 to n)
if (x[i-1] == y[j - 1])
dp[i][j] = dp[i-1][j-1] + 1;
else
dp[i][j] = dp[i][j-1];
And finally, the length of the longest subsequence of x which is substring of y is max(dp[i][n])
where 1 <= i <= m.
Below is implementation this approach:
C/C++
985
Chapter 133. Find length of longest subsequence of one string which is substring of
another string
Java
986
Chapter 133. Find length of longest subsequence of one string which is substring of
another string
// Else copy the previous value in the
// row i.e dp[i-1][j-1]
else
dp[i][j] = dp[i][j - 1];
}
}
// Finding the maximum length.
int ans = 0;
for (int i = 1; i <= m; i++)
ans = Math.max(ans, dp[i][n]);
return ans;
}
// Driver Method
public static void main(String[] args)
{
char x[] = "ABCD".toCharArray();
char y[] = "BACDBDCD".toCharArray();
int n = x.length, m = y.length;
System.out.println(maxSubsequenceSubstring(x, y, n, m));
}
}
C#
987
Chapter 133. Find length of longest subsequence of one string which is substring of
another string
// Calculating value for each element.
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
// If alphabet of string X and Y are
// equal make dp[i][j] = 1 + dp[i-1][j-1]
if (x[j - 1] == y[i - 1])
dp[i, j] = 1 + dp[i - 1, j - 1];
// Else copy the previous value in the
// row i.e dp[i-1][j-1]
else
dp[i, j] = dp[i, j - 1];
}
}
// Finding the maximum length.
int ans = 0;
for (int i = 1; i <= m; i++)
ans = Math.Max(ans, dp[i,n]);
return ans;
}
// Driver Method
public static void Main()
{
string x = "ABCD";
string y = "BACDBDCD";
int n = x.Length, m = y.Length;
Console.WriteLine(maxSubsequenceSubstring(x,
y, n, m));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find maximum length of
// subsequence of a string X such it is
// substring in another string Y.
// Return the maximum size of substring of
988
Chapter 133. Find length of longest subsequence of one string which is substring of
another string
// X which is substring in Y.
function maxSubsequenceSubstring($x, $y,
$n, $m)
{
$dp;
// Initialize the dp[][] to 0.
for ($i = 0; $i <= $m; $i++)
for ($j = 0; $j <= $n; $j++)
$dp[$i][$j] = 0;
// Calculating value for each element.
for ($i = 1; $i <= $m; $i++) {
for ( $j = 1; $j <= $n; $j++) {
// If alphabet of string
// X and Y are equal make
// dp[i][j] = 1 + dp[i-1][j-1]
if ($x[$j - 1] == $y[$i - 1])
$dp[$i][$j] = 1 + $dp[$i - 1][$j - 1];
// Else copy the previous
// value in the
// row i.e dp[i-1][j-1]
else
$dp[$i][$j] = $dp[$i][$j - 1];
}
}
// Finding the maximum length.
$ans = 0;
for ( $i = 1; $i <= $m; $i++)
$ans = max($ans, $dp[$i][$n]);
return $ans;
}
// Driver Code
{
$x = "ABCD";
$y = "BACDBDCD";
$n = strlen($x); $m = strlen($y);
echo maxSubsequenceSubstring($x, $y, $n, $m);
return 0;
}
// This code is contributed by nitin mittal
?>
989
Chapter 133. Find length of longest subsequence of one string which is substring of
another string
Output:
Source
https://www.geeksforgeeks.org/find-length-longest-subsequence-one-string-substring-another-string/
990
Chapter 134
Find length of the longest consecutive path from a given starting character - GeeksforGeeks
Given a matrix of characters. Find length of the longest path from a given character, such
that all characters in the path are consecutive to each other, i.e., every character in path is
next to previous in alphabetical order. It is allowed to move in all 8 directions from a cell.
Example
991
Chapter 134. Find length of the longest consecutive path from a given starting character
Output: 5
If starting point is 'e', then longest path with consecutive
characters is "e f g h i".
Output: 1
'c' is not present in all adjacent cells of 'b'
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to first search given starting character in the given matrix. Do Depth First
Search (DFS) from all occurrences to find all consecutive paths. While doing DFS, we may
encounter many subproblems again and again. So we use dynamic programming to store
results of subproblems.
Below is the implementation of above idea.
C++
992
Chapter 134. Find length of the longest consecutive path from a given starting character
return false;
return true;
}
// Check whether current character is adjacent to previous
// character (character processed in parent call) or not.
bool isadjacent(char prev, char curr)
{
return ((curr - prev) == 1);
}
// i, j are the indices of the current cell and prev is the
// character processed in the parent call.. also mat[i][j]
// is our current character.
int getLenUtil(char mat[R][C], int i, int j, char prev)
{
// If this cell is not valid or current character is not
// adjacent to previous one (e.g. d is not adjacent to b )
// or if this cell is already included in the path than return 0.
if (!isvalid(i, j) || !isadjacent(prev, mat[i][j]))
return 0;
// If this subproblem is already solved , return the answer
if (dp[i][j] != -1)
return dp[i][j];
int ans = 0; // Initialize answer
// recur for paths with differnt adjacent cells and store
// the length of longest path.
for (int k=0; k<8; k++)
ans = max(ans, 1 + getLenUtil(mat, i + x[k],
j + y[k], mat[i][j]));
// save the answer and return
return dp[i][j] = ans;
}
// Returns length of the longest path with all characters consecutive
// to each other. This function first initializes dp array that
// is used to store results of subproblems, then it calls
// recursive DFS based function getLenUtil() to find max length path
int getLen(char mat[R][C], char s)
{
memset(dp, -1, sizeof dp);
int ans = 0;
for (int i=0; i<R; i++)
993
Chapter 134. Find length of the longest consecutive path from a given starting character
{
for (int j=0; j<C; j++)
{
// check for each possible starting point
if (mat[i][j] == s) {
// recur for all eight adjacent cells
for (int k=0; k<8; k++)
ans = max(ans, 1 + getLenUtil(mat,
i + x[k], j + y[k], s));
}
}
}
return ans;
}
// Driver program
int main() {
char mat[R][C] = { {'a','c','d'},
{ 'h','b','a'},
{ 'i','g','f'}};
cout << getLen(mat, 'a') << endl;
cout << getLen(mat, 'e') << endl;
cout << getLen(mat, 'b') << endl;
cout << getLen(mat, 'f') << endl;
return 0;
}
Java
class path
{
// tool matrices to recur for adjacent cells.
static int x[] = {0, 1, 1, -1, 1, 0, -1, -1};
static int y[] = {1, 0, 1, 1, -1, -1, 0, -1};
static int R = 3;
static int C = 3;
// dp[i][j] Stores length of longest consecutive path
// starting at arr[i][j].
static int dp[][] = new int[R][C];
// check whether mat[i][j] is a valid cell or not.
static boolean isvalid(int i, int j)
{
if (i < 0 || j < 0 || i >= R || j >= C)
return false;
994
Chapter 134. Find length of the longest consecutive path from a given starting character
return true;
}
// Check whether current character is adjacent to previous
// character (character processed in parent call) or not.
static boolean isadjacent(char prev, char curr)
{
return ((curr - prev) == 1);
}
// i, j are the indices of the current cell and prev is the
// character processed in the parent call.. also mat[i][j]
// is our current character.
static int getLenUtil(char mat[][], int i, int j, char prev)
{
// If this cell is not valid or current character is not
// adjacent to previous one (e.g. d is not adjacent to b )
// or if this cell is already included in the path than return 0.
if (!isvalid(i, j) || !isadjacent(prev, mat[i][j]))
return 0;
// If this subproblem is already solved , return the answer
if (dp[i][j] != -1)
return dp[i][j];
int ans = 0; // Initialize answer
// recur for paths with differnt adjacent cells and store
// the length of longest path.
for (int k=0; k<8; k++)
ans = Math.max(ans, 1 + getLenUtil(mat, i + x[k],
j + y[k], mat[i][j]));
// save the answer and return
return dp[i][j] = ans;
}
// Returns length of the longest path with all characters consecutive
// to each other. This function first initializes dp array that
// is used to store results of subproblems, then it calls
// recursive DFS based function getLenUtil() to find max length path
static int getLen(char mat[][], char s)
{
//assigning all dp values to -1
for(int i = 0;i<R;++i)
for(int j = 0;j<C;++j)
dp[i][j] = -1;
995
Chapter 134. Find length of the longest consecutive path from a given starting character
int ans = 0;
for (int i=0; i<R; i++)
{
for (int j=0; j<C; j++)
{
// check for each possible starting point
if (mat[i][j] == s) {
// recur for all eight adjacent cells
for (int k=0; k<8; k++)
ans = Math.max(ans, 1 + getLenUtil(mat,
i + x[k], j + y[k], s));
}
}
}
return ans;
}
public static void main(String args[])
{
char mat[][] = { {'a','c','d'},
{ 'h','b','a'},
{ 'i','g','f'}};
System.out.println(getLen(mat, 'a') );
System.out.println(getLen(mat, 'e') );
System.out.println(getLen(mat, 'b') );
System.out.println(getLen(mat, 'f') );
}
}/* This code is contributed by Rajat Mishra */
C#
996
Chapter 134. Find length of the longest consecutive path from a given starting character
997
Chapter 134. Find length of the longest consecutive path from a given starting character
// save the answer and return
return dp[i,j] = ans;
}
// Returns length of the longest path
// with all characters consecutive to
// each other. This function first
// initializes dp array that is used
// to store results of subproblems,
// then it calls recursive DFS based
// function getLenUtil() to find max
// length path
static int getLen(char [,]mat, char s)
{
//assigning all dp values to -1
for(int i = 0; i < R; ++i)
for(int j = 0; j < C; ++j)
dp[i,j] = -1;
int ans = 0;
for (int i=0; i<R; i++)
{
for (int j=0; j<C; j++)
{
// check for each possible
// starting point
if (mat[i,j] == s) {
// recur for all eight
// adjacent cells
for (int k = 0; k < 8; k++)
ans = Math.Max(ans, 1 +
getLenUtil(mat, i +
x[k], j + y[k], s));
}
}
}
return ans;
}
// Driver code`
public static void Main()
{
char [,]mat = { {'a','c','d'},
998
Chapter 134. Find length of the longest consecutive path from a given starting character
{ 'h','b','a'},
{ 'i','g','f'}};
Console.WriteLine(getLen(mat, 'a') );
Console.WriteLine(getLen(mat, 'e') );
Console.WriteLine(getLen(mat, 'b') );
Console.WriteLine(getLen(mat, 'f') );
}
}
// This code is contributed by nitin mittal.
Output:
4
0
3
4
Source
https://www.geeksforgeeks.org/find-length-of-the-longest-consecutive-path-in-a-character-matrix/
999
Chapter 135
Find longest bitonic sequence such that increasing and decreasing parts are from two differ-
ent arrays - GeeksforGeeks
We are given two arrays, we need to find the longest possiblebitonic sequence such that
increasing part must be from first array and should be a subsequence of first array. Similarly,
decreasing part of must be from second array and should be a subsequence of it.
Examples:
The idea is to use largest increasing sequence from array1 and largest decreasing sequence
from array2 and then combine both to get our result.
1000
Chapter 135. Find longest bitonic sequence such that increasing and decreasing parts are
from two different arrays
vector<int> res;
// utility Binary search
int GetCeilIndex(int arr[], vector<int>& T, int l,
int r, int key)
{
while (r - l > 1) {
int m = l + (r - l) / 2;
if (arr[T[m]] >= key)
r = m;
else
l = m;
}
return r;
}
// function to find LIS in reverse form
void LIS(int arr[], int n)
{
// Add boundary case, when array n is zero
// Depend on smart pointers
vector<int> tailIndices(n, 0); // Initialized with 0
vector<int> prevIndices(n, -1); // initialized with -1
int len = 1; // it will always point to empty location
for (int i = 1; i < n; i++) {
// new smallest value
if (arr[i] < arr[tailIndices[0]])
tailIndices[0] = i;
// arr[i] wants to extend largest subsequence
else if (arr[i] > arr[tailIndices[len - 1]]) {
prevIndices[i] = tailIndices[len - 1];
tailIndices[len++] = i;
}
// arr[i] wants to be a potential candidate of
// future subsequence
// It will replace ceil value in tailIndices
else {
int pos = GetCeilIndex(arr, tailIndices, -1,
len - 1, arr[i]);
prevIndices[i] = tailIndices[pos - 1];
tailIndices[pos] = i;
}
}
1001
Chapter 135. Find longest bitonic sequence such that increasing and decreasing parts are
from two different arrays
// put LIS into vector
for (int i = tailIndices[len - 1]; i >= 0; i = prevIndices[i])
res.push_back(arr[i]);
}
// function for finding longest bitonic seq
void longestBitonic(int arr1[], int n1, int arr2[], int n2)
{
// find LIS of array 1 in reverse form
LIS(arr1, n1);
// reverse res to get LIS of first array
reverse(res.begin(), res.end());
// reverse array2 and find its LIS
reverse(arr2, arr2 + n2);
LIS(arr2, n2);
// print result
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
}
// driver preogram
int main()
{
int arr1[] = { 1, 2, 4, 3, 2 };
int arr2[] = { 8, 6, 4, 7, 8, 9 };
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int n2 = sizeof(arr2) / sizeof(arr2[0]);
longestBitonic(arr1, n1, arr2, n2);
return 0;
}
Output:
1 2 3 8 6 4
Source
https://www.geeksforgeeks.org/find-longest-bitonic-sequence-increasing-decreasing-parts-two-different-arrays/
1002
Chapter 136
1003
Chapter 136. Find maximum length Snake sequence
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to use Dynamic Programming. For each cell of the matrix, we keep maximum
length of a snake which ends in current cell. The maximum length snake sequence will have
maximum value. The maximum value cell will correspond to tail of the snake. In order to
print the snake, we need to backtrack from tail all the way back to snake’s head.
Let T[i][i] represent maximum length of a snake which ends at cell (i, j), then for given
matrix M, the DP relation is defined as –
T[0][0] = 0
T[i][j] = max(T[i][j], T[i][j – 1] + 1) if M[i][j] = M[i][j – 1] ± 1
T[i][j] = max(T[i][j], T[i – 1][j] + 1) if M[i][j] = M[i – 1][j] ± 1
Below is C++ implementation of the idea –
CPP
1004
Chapter 136. Find maximum length Snake sequence
list<Point> path;
Point pt = {i, j};
path.push_front(pt);
while (grid[i][j] != 0)
{
if (i > 0 &&
grid[i][j] - 1 == grid[i - 1][j])
{
pt = {i - 1, j};
path.push_front(pt);
i--;
}
else if (j > 0 &&
grid[i][j] - 1 == grid[i][j - 1])
{
pt = {i, j - 1};
path.push_front(pt);
j--;
}
}
return path;
}
// Function to find maximum length Snake sequence
void findSnakeSequence(int mat[M][N])
{
// table to store results of subproblems
int lookup[M][N];
// initialize by 0
memset(lookup, 0, sizeof lookup);
// stores maximum length of Snake sequence
int max_len = 0;
// store cordinates to snake's tail
int max_row = 0;
int max_col = 0;
// fill the table in bottom-up fashion
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
// do except for (0, 0) cell
1005
Chapter 136. Find maximum length Snake sequence
if (i || j)
{
// look above
if (i > 0 &&
abs(mat[i - 1][j] - mat[i][j]) == 1)
{
lookup[i][j] = max(lookup[i][j],
lookup[i - 1][j] + 1);
if (max_len < lookup[i][j])
{
max_len = lookup[i][j];
max_row = i, max_col = j;
}
}
// look left
if (j > 0 &&
abs(mat[i][j - 1] - mat[i][j]) == 1)
{
lookup[i][j] = max(lookup[i][j],
lookup[i][j - 1] + 1);
if (max_len < lookup[i][j])
{
max_len = lookup[i][j];
max_row = i, max_col = j;
}
}
}
}
}
cout << "Maximum length of Snake sequence is: "
<< max_len << endl;
// find maximum length Snake sequence path
list<Point> path = findPath(lookup, mat, max_row,
max_col);
cout << "Snake sequence is:";
for (auto it = path.begin(); it != path.end(); it++)
cout << endl << mat[it->x][it->y] << " ("
<< it->x << ", " << it->y << ")" ;
}
// Driver code
int main()
{
1006
Chapter 136. Find maximum length Snake sequence
int mat[M][N] =
{
{9, 6, 5, 2},
{8, 7, 6, 5},
{7, 3, 1, 6},
{1, 1, 1, 7},
};
findSnakeSequence(mat);
return 0;
}
Python3
1007
Chapter 136. Find maximum length Snake sequence
1008
Chapter 136. Find maximum length Snake sequence
[8, 7, 6, 5],
[7, 3, 1, 6],
[1, 1, 1, 7]]
findSnakeSequence(mat)
# This code is contributed
# by Soumen Ghosh
Output :
Time complexity of above solution is O(M*N). Auxiliary space used by above solution is
O(M*N). If we are not required to print the snake, space can be further reduced to O(N)
as we only uses the result from last row.
Reference: Stack Overflow
Source
https://www.geeksforgeeks.org/find-maximum-length-snake-sequence/
1009
Chapter 137
While reaching house i thief has two options, either he robs it or leave it. Let dp[i] represents
the maximum value stolen so far on reaching house i. We can calculate the value of dp[i] as
following –
1010
Chapter 137. Find maximum possible stolen value from houses
Thief will consider both options and decide whether to rob or not and maximum of both
values will be the maximum stolen value till reaching house i.
We can prepare dp in bottom up manner instead of recursively. Following is the program
for that –
C++
1011
Chapter 137. Find maximum possible stolen value from houses
Java
1012
Chapter 137. Find maximum possible stolen value from houses
Python
C#
1013
Chapter 137. Find maximum possible stolen value from houses
class GFG
{
// Function to calculate the
// maximum stolen value
static int maxLoot(int []hval, int n)
{
if (n == 0)
return 0;
if (n == 1)
return hval[0];
if (n == 2)
return Math.Max(hval[0], hval[1]);
// dp[i] represent the maximum value stolen
// so far after reaching house i.
int[] dp = new int[n];
// Initialize the dp[0] and dp[1]
dp[0] = hval[0];
dp[1] = Math.Max(hval[0], hval[1]);
// Fill remaining positions
for (int i = 2; i<n; i++)
dp[i] = Math.Max(hval[i]+dp[i-2], dp[i-1]);
return dp[n-1];
}
// Driver program
public static void Main ()
{
int []hval = {6, 7, 1, 3, 8, 2, 4};
int n = hval.Length;
Console.WriteLine("Maximum loot value : " +
maxLoot(hval, n));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to find
// the maximum stolen value
// calculate the maximum
// stolen value
1014
Chapter 137. Find maximum possible stolen value from houses
Output:
Time complexity =
Space complexity =
1015
Chapter 137. Find maximum possible stolen value from houses
We can optimize extra space, by using two variables to store value dp[i-1] and dp[i-2].
Following is the program for that –
C++
1016
Chapter 137. Find maximum possible stolen value from houses
Java
Python
1017
Chapter 137. Find maximum possible stolen value from houses
C#
1018
Chapter 137. Find maximum possible stolen value from houses
PHP
<?php
// PHP program to find
// the maximum stolen value
// calculate the
// maximum stolen value
1019
Chapter 137. Find maximum possible stolen value from houses
Output:
Time complexity =
1020
Chapter 137. Find maximum possible stolen value from houses
Auxiliary Space =
Improved By : Sam007, jit_t
Source
https://www.geeksforgeeks.org/find-maximum-possible-stolen-value-houses/
1021
Chapter 138
Input :
n = 5, m = 6
arr[][m] = {{3, 2, 3, 5},
{2, 7, -1},
{2, 8, 10},
{4, 5, 2, 6, 1},
{3, 2, 3, -2}};
Output : Maximum sum can be obtained is 39
Explanation : We are allowed to pick at most
one subarray from every array.
We get total sum 39 as ((5) + (7) + (8 + 10) +
(4 + 5))
Input :
n = 3, m = 4
arr[][m] = {{2, 3, 2},
{3, -1, 7, 10},
{4, 8, 10, -5, 3}};
Output : Maximum sum can be obtained is 35
1022
Chapter 138. Find maximum sum array of length less than or equal to m
This problem is similar to Knapsack problem.where you have to either pick an element or
leave it. We will have the same strategy here.
Given that the total number of elements in these n arrays is atmost 10^5. It is also known
that m is atmost 10^3 and the input arrays can contain negative numbers. First, make a
DP table (2D array) of size n * m and then, pre-compute the cumulative sum of an array
so that maximum sum of every length from 1 to n of that array can be easily computed, so
that for every given array there can be a maximum contiguous sum for length k, where k is
from 1 to length of the array.
In detail, process input arrays one by one. First, compute the maximum sum subarrays
of processed array for all sizes from 1 to length. Then, update our dynamic programming
table with these values and we start processing the next array.
Algorithm :
Source
https://www.geeksforgeeks.org/find-maximum-sum-array-length-less-equal-m/
1023
Chapter 139
In order to minimize the adjustment cost ∑|A[i] – Anew [i]| for all index i in the array,
|A[i] – Anew [i]| should be as close to zero as possible. Also, |A[i] – Anew [i+1] ]| � Target.
1024
Chapter 139. Find minimum adjustment cost of an array
1025
Chapter 139. Find minimum adjustment cost of an array
}
}
// return minimum value from last row of dp table
int res = INT_MAX;
for (int j = 0; j <= M; j++)
res = min(res, dp[n - 1][j]);
return res;
}
// Driver Program to test above functions
int main()
{
int arr[] = {55, 77, 52, 61, 39, 6, 25, 60, 49, 47};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 10;
cout << "Minimum adjustment cost is "
<< minAdjustmentCost(arr, n, target) << endl;
return 0;
}
Java
1026
Chapter 139. Find minimum adjustment cost of an array
C#
1027
Chapter 139. Find minimum adjustment cost of an array
1028
Chapter 139. Find minimum adjustment cost of an array
// Driver program
public static void Main ()
{
int []arr = {55, 77, 52, 61, 39,
6, 25, 60, 49, 47};
int n = arr.Length;
int target = 10;
Console.WriteLine("Minimum adjustment"
+ " cost is "
+ minAdjustmentCost(arr, n, target));
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to find minimum
// adjustment cost of an array
$M = 100;
// Function to find minimum
// adjustment cost of an array
function minAdjustmentCost( $A, $n, $target)
{
// dp[i][j] stores minimal
// adjustment cost on changing
// A[i] to j
global $M;
$dp = array(array());
// handle first element
// of array seperately
for($j = 0; $j <= $M; $j++)
$dp[0][$j] = abs($j - $A[0]);
// do for rest
// elements of the array
for($i = 1; $i < $n; $i++)
{
// replace A[i] to j and
// calculate minimal adjustment
1029
Chapter 139. Find minimum adjustment cost of an array
Output:
1030
Chapter 139. Find minimum adjustment cost of an array
Source
https://www.geeksforgeeks.org/find-minimum-adjustment-cost-of-an-array/
1031
Chapter 140
This problem is a variation of the problem discussed Coin Change Problem. Here instead
of finding total number of possible solutions, we need to find the solution with minimum
number of coins.
The minimum number of coins for a value V can be computed using below recursive formula.
1032
Chapter 140. Find minimum number of coins that make a given value
C++
Java
1033
Chapter 140. Find minimum number of coins that make a given value
Python3
1034
Chapter 140. Find minimum number of coins that make a given value
return 0
# Initialize result
res = sys.maxsize
# Try every coin that has smaller value than V
for i in range(0, m):
if (coins[i] <= V):
sub_res = minCoins(coins, m, V-coins[i])
# Check for INT_MAX to avoid overflow and see if
# result can minimized
if (sub_res != sys.maxsize and sub_res + 1 < res):
res = sub_res + 1
return res
# Driver program to test above function
coins = [9, 6, 5, 1]
m = len(coins)
V = 11
print("Minimum coins required is",minCoins(coins, m, V))
# This code is contributed by
# Smitha Dinesh Semwal
C#
1035
Chapter 140. Find minimum number of coins that make a given value
PHP
<?php
// A Naive recursive PHP
// program to find minimum
// of coins to make a given
// change V
// m is size of coins array
// (number of different coins)
function minCoins($coins,
$m, $V)
{
// base case
if ($V == 0) return 0;
1036
Chapter 140. Find minimum number of coins that make a given value
// Initialize result
$res = PHP_INT_MAX;
// Try every coin that has
// smaller value than V
for ($i = 0; $i < $m; $i++)
{
if ($coins[$i] <= $V)
{
$sub_res = minCoins($coins, $m,
$V - $coins[$i]);
// Check for INT_MAX to
// avoid overflow and see
// if result can minimized
if ($sub_res != PHP_INT_MAX &&
$sub_res + 1 < $res)
$res = $sub_res + 1;
}
}
return $res;
}
// Driver Code
$coins = array(9, 6, 5, 1);
$m = sizeof($coins);
$V = 11;
echo "Minimum coins required is ",
minCoins($coins, $m, $V);
// This code is contributed by ajit
?>
Output:
The time complexity of above solution is exponential. If we draw the complete recursion
tree, we can observer that many subproblems are solved again and again. For example,
when we start from V = 11, we can reach 6 by subtracting one 5 times and by subtracting
5 one times. So the subproblem for 6 is called twice.
Since same suproblems are called again, this problem has Overlapping Subprolems property.
So the min coins problem has both properties (see thisand this) of a dynamic programming
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. Below is Dynamic Programming based solution.
C++
1037
Chapter 140. Find minimum number of coins that make a given value
Java
1038
Chapter 140. Find minimum number of coins that make a given value
1039
Chapter 140. Find minimum number of coins that make a given value
C#
1040
Chapter 140. Find minimum number of coins that make a given value
PHP
<?php
// A Dynamic Programming based
// PHP program to find minimum
// of coins to make a given
// change V.
// m is size of coins
// array (number of different coins)
function minCoins($coins, $m, $V)
{
// table[i] will be storing the
// minimum number of coins
// required for i value. So
// table[V] will have result
$table[$V + 1] = array();
// Base case (If given
// value V is 0)
$table[0] = 0;
1041
Chapter 140. Find minimum number of coins that make a given value
// Initialize all table
// values as Infinite
for ($i = 1; $i <= $V; $i++)
$table[$i] = PHP_INT_MAX;
// Compute minimum coins
// required for all
// values from 1 to V
for ($i = 1; $i <= $V; $i++)
{
// Go through all coins
// smaller than i
for ($j = 0; $j < $m; $j++)
if ($coins[$j] <= $i)
{
$sub_res = $table[$i - $coins[$j]];
if ($sub_res != PHP_INT_MAX &&
$sub_res + 1 < $table[$i])
$table[$i] = $sub_res + 1;
}
}
return $table[$V];
}
// Driver Code
$coins = array(9, 6, 5, 1);
$m = sizeof($coins);
$V = 11;
echo "Minimum coins required is ",
minCoins($coins, $m, $V);
// This code is contributed by ajit
?>
Output:
1042
Chapter 140. Find minimum number of coins that make a given value
Source
https://www.geeksforgeeks.org/find-minimum-number-of-coins-that-make-a-change/
1043
Chapter 141
Find minimum possible size of array with given rules for removing elements - GeeksforGeeks
Given an array of numbers and a constant k, minimize size of array with following rules for
removing elements.
Example:
Source: https://code.google.com/codejam/contest/4214486/dashboard#s=p2
We strongly recommend you to minimize your browser and try this yourself
first.
1044
Chapter 141. Find minimum possible size of array with given rules for removing elements
4) Return result
The time complexity of above solution is exponential. If we draw the complete recursion
tree, we can observer that many subproblems are solved again and again. Since same
suproblems are called again, this problem has Overlapping Subprolems property. Like other
typical Dynamic Programming(DP) problems, recomputations of same subproblems can be
avoided by constructing a temporary array dp[][] to store results of the subproblems. Below
is Dynamic Programming based solution
Below is C++ implementation of above idea. The implementation is memoization based,
i.e., it is recursive and uses a lookup table dp[][] to check if a subproblem is already solved
or not.
1045
Chapter 141. Find minimum possible size of array with given rules for removing elements
1046
Chapter 141. Find minimum possible size of array with given rules for removing elements
Output:
This article is contributed by Ekta Goel. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-minimum-possible-size-of-array-with-given-rules-for-removal/
1047
Chapter 142
Find minimum sum such that one of every three consecutive elements is taken - Geeks-
forGeeks
Given an array of n non-negative numbers, the task is to find the minimum sum of elements
(picked from the array) such that at least one element is picked out of every 3 consecutive
elements in the array.
Examples :
Let sum(i) be the minimum possible sum when arr[i] is part of a solution sum (not necessarily
result) and is last picked element. Then our result is minimum of sum(n-1), sum(n-2) and
1048
Chapter 142. Find minimum sum such that one of every three consecutive elements is
taken
sum(n-3) [We must pick at least one of the last three elements].
We can recursively compute sum(i) as sum of arr[i] and minimum(sum(i-1), sum(i-2), sum(i-
3)). Since there are overlapping subproblems in recursive structure of problem, we can use
Dynamic Programming to solve this problem.
Below is the implementation of above idea.
C++
1049
Chapter 142. Find minimum sum such that one of every three consecutive elements is
taken
// Driver code
int main()
{
int arr[] = {1, 2, 3, 20, 2, 10, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Min Sum is " << findMinSum(arr, n);
return 0;
}
Java
1050
Chapter 142. Find minimum sum such that one of every three consecutive elements is
taken
Python3
1051
Chapter 142. Find minimum sum such that one of every three consecutive elements is
taken
C#
1052
Chapter 142. Find minimum sum such that one of every three consecutive elements is
taken
PHP
<?php
// A Dynamic Programming based
// PHP program to find minimum
// possible sum of elements of
// array such that an element
// out of every three consecutive
// is picked.
// function to find minimum of
// 3 elements
function minimum($a, $b, $c)
{
return min(min($a, $b), $c);
}
// Returns minimum possible sum
// of elements such that an
// element out of every three
// consecutive elements is picked.
function findMinSum($arr, $n)
{
// Create a DP table to store results of
// subproblems. sum[i] is going to store
// minimum possible sum when arr[i] is
// part of the solution.
$sum[$n] = 0;
// When there are less
// than or equal to
// 3 elements
1053
Chapter 142. Find minimum sum such that one of every three consecutive elements is
taken
$sum[0] = $arr[0];
$sum[1] = $arr[1];
$sum[2] = $arr[2];
// Iterate through all other elements
for ($i = 3; $i < $n; $i++)
$sum[$i] = $arr[$i] + minimum($sum[$i - 3],
$sum[$i - 2], $sum[$i - 1]);
return minimum($sum[$n - 1], $sum[$n - 2],
$sum[$n - 3]);
}
// Driver code
$arr = array(1, 2, 3, 20, 2, 10, 1);
$n = sizeof($arr);
echo "Min Sum is " , findMinSum($arr, $n);
// This code is contributed by nitin mittal.
?>
Output:
Min Sum is 4
Source
https://www.geeksforgeeks.org/find-minimum-sum-one-every-three-consecutive-elements-taken/
1054
Chapter 143
Examples :
Input : n = 7
Output : 3
1055
Chapter 143. Find n-th element from Stern’s Diatomic Series
Input : n = 15
Output : 4
Approach :
We solve this problem with a very simple concept of Dynamic programming which is used
in finding fibonacci numbers. After saving the base case of DP[0] = 0, DP[1] = 1, we have
to simply traverse from i = 2 to n and compute DP[i] as per explained definition of Stern’s
diatomic series. And finally return the value of DP[n].
Algorithm :
C++
1056
Chapter 143. Find n-th element from Stern’s Diatomic Series
Java
1057
Chapter 143. Find n-th element from Stern’s Diatomic Series
if (i % 2 == 0)
DP[i] = DP[i / 2];
// Case 2: for odd n
else
DP[i] = DP[(i - 1) / 2] +
DP[(i + 1) / 2];
}
return DP[n];
}
// Driver program
public static void main(String[] args)
{
int n = 15;
System.out.println(findSDSFunc(n));
}
}
// This code is contributed by Smita Semwal.
Python 3
1058
Chapter 143. Find n-th element from Stern’s Diatomic Series
else:
DP[i] = (DP[int((i - 1) / 2)]
+ DP[int((i + 1) / 2)])
return DP[n]
# Driver program
n = 15
print(findSDSFunc(n))
# This code is contribute by
# Smitha Dinesh Semwal
C#
1059
Chapter 143. Find n-th element from Stern’s Diatomic Series
}
return DP[n];
}
// Driver Code
static public void Main ()
{
int n = 15;
Console.WriteLine(findSDSFunc(n));
}
}
// This code is contributed by aj_36
PHP
<?php
// PHP Program to find the nth element
// of Stern's Diatomic Series
// function to find nth stern'
// diatomic series
function findSDSFunc($n)
{
// SET the Base case
$DP[0] = 0;
$DP[1] = 1;
// Traversing the array from
// 2nd Element to nth Element
for ($i = 2; $i <= $n; $i++)
{
// Case 1: for even n
if ($i % 2 == 0)
$DP[$i] = $DP[$i / 2];
// Case 2: for odd n
else
$DP[$i] = $DP[($i - 1) / 2] +
$DP[($i + 1) / 2];
}
return $DP[$n];
}
// Driver Code
1060
Chapter 143. Find n-th element from Stern’s Diatomic Series
$n = 15;
echo(findSDSFunc($n));
// This code is contributed by Ajit.
?>
Output:
Source
https://www.geeksforgeeks.org/find-n-th-element-from-sterns-diatomic-series/
1061
Chapter 144
Input : 0 1 0
1 1 1
0 1 1
Output : 4
Endless points are (1, 1), (1, 2),
(2, 1) and (2, 2). For all other
points path to some corner is
blocked at some point.
Input : 0 1 1
1 1 0
0 1 0
Output : 1
Endless point is (0, 2).
Naive Approach :
We traverse all positions, for every position, we check that does this position has endless
path or not. If yes then count it otherwise ignore it. But as usual its time complexity seems
to be high.
Time complexity : O(n3 )
1062
Chapter 144. Find number of endless points
Also, we can say that any position (i,j) will have an endless row if (i,j+1) will have an endless
row and value of (i,j) is 1.
Similarly, we can say that any position (i,j) will have an endless column if (i+1,j) will have
an endless column and value of (i,j) is 1.
So we should maintain two matrices one for row and one for column. Always start from
right most position for row and bottom most position for column and only check for next
position whether it has endless path or not.
And Finally, if any position will have an endless path in both row and column matrix then
that position is said to have an endless path.
C++
1063
Chapter 144. Find number of endless points
#include<bits/stdc++.h>
using namespace std;
const int MAX = 100;
// Returns count of endless points
int countEndless(bool input[][MAX], int n)
{
bool row[n][n], col[n][n];
// Fills column matrix. For every column, start
// from every last row and fill every entry as
// blockage after a 0 is found.
for (int j=0; j<n; j++)
{
// flag which will be zero once we get a '0'
// and it will be 1 otherwise
bool isEndless = 1;
for (int i=n-1; i>=0; i--)
{
// encountered a '0', set the isEndless
// variable to false
if (input[i][j] == 0)
isEndless = 0;
col[i][j] = isEndless;
}
}
// Similarly, fill row matrix
for (int i=0; i<n; i++)
{
bool isEndless = 1;
for (int j= n-1; j>=0; j--)
{
if (input[i][j] == 0)
isEndless = 0;
row[i][j] = isEndless;
}
}
// Calculate total count of endless points
int ans = 0;
for (int i=0; i<n; i++)
for (int j=1; j<n; j++)
// If there is NO blockage in row
// or column after this point,
// increment result.
1064
Chapter 144. Find number of endless points
Java
1065
Chapter 144. Find number of endless points
isEndless = false;
col[i][j] = isEndless;
}
}
// Similarly, fill row matrix
for (int i = 0; i < n; i++)
{
boolean isEndless = true;
for (int j = n-1; j >= 0; j--)
{
if (input[i][j] == false)
isEndless = false;
row[i][j] = isEndless;
}
}
// Calculate total count of endless points
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = 1; j < n; j++)
// If there is NO blockage in row
// or column after this point,
// increment result.
if (row[i][j] && col[i][j])
ans++;
return ans;
}
//driver code
public static void main(String arg[])
{
boolean input[][] = {
{true, false, true, true},
{false, true, true, true},
{true, true, true, true},
{false, true, true, false}};
int n = 4;
System.out.print(countEndless(input, n));
}
}
// This code is contributed by Anant Agarwal.
1066
Chapter 144. Find number of endless points
C#
1067
Chapter 144. Find number of endless points
}
}
// Calculate total count of
// endless points
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = 1; j < n; j++)
// If there is NO blockage
// in row or column after
// this point, increment
// result.
if (row[i,j] && col[i,j])
ans++;
return ans;
}
//Driver code
public static void Main()
{
bool [,]input = {
{true, false, true, true},
{false, true, true, true},
{true, true, true, true},
{false, true, true, false}};
int n = 4;
Console.Write(countEndless(input, n));
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to find
// count of endless points
// Returns count of
// endless points
function countEndless($input, $n)
{
// Fills column matrix. For
// every column, start from
1068
Chapter 144. Find number of endless points
1069
Chapter 144. Find number of endless points
// Driver code
$input = array(array(1, 0, 1, 1),
array(0, 1, 1, 1),
array(1, 1, 1, 1),
array(0, 1, 1, 0));
$n = 4;
echo countEndless($input, $n);
// This code is contributed
// by shiv_bhakt.
?>
Output:
Source
https://www.geeksforgeeks.org/find-number-endless-points/
1070
Chapter 145
We strongly recommend you to minimize your browser and try this yourself
first.
We can solve this problem recursively. The idea is to subtract first coefficient from rhs and
then recur for remaining value of rhs.
If rhs = 0
countSol(coeff, 0, rhs, n-1) = 1
Else
1071
Chapter 145. Find number of solutions of a linear equation of n variables
Java
1072
Chapter 145. Find number of solutions of a linear equation of n variables
Python3
1073
Chapter 145. Find number of solutions of a linear equation of n variables
C#
1074
Chapter 145. Find number of solutions of a linear equation of n variables
PHP
<?php
// A naive recursive PHP program to
// find number of non-negative solutions
// for a given linear equation
// Recursive function thet returns count
// of solutions for given rhs value and
// coefficients coeff[start..end]
function countSol($coeff, $start, $end, $rhs)
{
// Base case
1075
Chapter 145. Find number of solutions of a linear equation of n variables
if ($rhs == 0)
return 1;
// Initialize count of solutions
$result = 0;
// One by subtract all smaller or
// equal coefficiants and recur
for ($i = $start; $i <= $end; $i++)
if ($coeff[$i] <= $rhs)
$result += countSol($coeff, $i, $end,
$rhs - $coeff[$i]);
return $result;
}
// Driver Code
$coeff = array (2, 2, 5);
$rhs = 4;
$n = sizeof($coeff);
echo countSol($coeff, 0, $n - 1, $rhs);
// This code is contributed by ajit
?>
Output :
The time complexity of above solution is exponential. We can solve this problem in Pseudo
Polynomial Time (time complexity is dependent on numeric value of input) using Dynamic
Programming. The idea is similar to Dynamic Programming solution Subset Sum problem.
Below is Dynamic Programming based implementation.
C++
1076
Chapter 145. Find number of solutions of a linear equation of n variables
Java
1077
Chapter 145. Find number of solutions of a linear equation of n variables
return dp[rhs];
}
// Driver code
public static void main (String[] args)
{
int coeff[] = {2, 2, 5};
int rhs = 4;
int n = coeff.length;
System.out.print(countSol(coeff, n, rhs));
}
}
// This code is contributed by Anant Agarwal
Python3
C#
1078
Chapter 145. Find number of solutions of a linear equation of n variables
PHP
1079
Chapter 145. Find number of solutions of a linear equation of n variables
<?php
// PHP program to find number of
// non-negative solutions for a
// given linear equation
// Returns count of solutions
// for given rhs and coefficients
// coeff[0..n-1]
function countSol($coeff, $n, $rhs)
{
// Create and initialize a table
// to store results of subproblems
$dp = str_repeat ("\0", 256);
$dp[0] = 1;
// Fill table in
// bottom up manner
for ($i = 0; $i < $n; $i++)
for ($j = $coeff[$i];
$j <= $rhs; $j++)
$dp[$j] = $dp[$j] + ($dp[$j -
$coeff[$i]]);
return $dp[$rhs];
}
// Driver Code
$coeff = array(2, 2, 5);
$rhs = 4;
// $n = count($coeff);
$n = sizeof($coeff) / sizeof($coeff[0]);
echo countSol($coeff, $n, $rhs);
// This code is contributed
// by shiv_bhakt.
?>
Output :
1080
Chapter 145. Find number of solutions of a linear equation of n variables
Source
https://www.geeksforgeeks.org/find-number-of-solutions-of-a-linear-equation-of-n-variables/
1081
Chapter 146
Input:
string a = "GeeksforGeeks"
string b = "Gks"
Output: 4
Explanation:
The four strings are - (Check characters marked in bold)
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
If we carefully analyze the given problem, we can see that it can be easily divided into
sub-problems. The idea is to process all characters of both strings one by one staring from
either from left or right side. Let us traverse from right corner, there are two possibilities
for every pair of character being traversed.
1082
Chapter 146. Find number of times a string occurs as a subsequence in given string
C++
1083
Chapter 146. Find number of times a string occurs as a subsequence in given string
Java
1084
Chapter 146. Find number of times a string occurs as a subsequence in given string
return count(a, b, m - 1, n - 1) +
count(a, b, m - 1, n);
else
// If last characters are different,
// ignore last char of first string
// and recur for remaining string
return count(a, b, m - 1, n);
}
// Driver code
public static void main (String[] args)
{
String a = "GeeksforGeeks";
String b = "Gks";
System.out.println( count(a, b, a.length(), b.length())) ;
}
}
// This code is contributed by vt_m
C#
1085
Chapter 146. Find number of times a string occurs as a subsequence in given string
Output:
C++
1086
Chapter 146. Find number of times a string occurs as a subsequence in given string
// Iterative DP function to find the number of times
// the second string occurs in the first string,
// whether continuous or discontinuous
int count(string a, string b)
{
int m = a.length();
int n = b.length();
// Create a table to store results of sub-problems
int lookup[m + 1][n + 1] = { { 0 } };
// If first string is empty
for (int i = 0; i <= n; ++i)
lookup[0][i] = 0;
// If second string is empty
for (int i = 0; i <= m; ++i)
lookup[i][0] = 1;
// Fill lookup[][] in bottom up manner
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
// If last characters are same, we have two
// options -
// 1. consider last characters of both strings
// in solution
// 2. ignore last character of first string
if (a[i - 1] == b[j - 1])
lookup[i][j] = lookup[i - 1][j - 1] +
lookup[i - 1][j];
else
// If last character are different, ignore
// last character of first string
lookup[i][j] = lookup[i - 1][j];
}
}
return lookup[m][n];
}
// Driver code
int main()
{
string a = "GeeksforGeeks";
1087
Chapter 146. Find number of times a string occurs as a subsequence in given string
string b = "Gks";
cout << count(a, b);
return 0;
}
Java
1088
Chapter 146. Find number of times a string occurs as a subsequence in given string
Output:
1089
Chapter 146. Find number of times a string occurs as a subsequence in given string
Source
https://www.geeksforgeeks.org/find-number-times-string-occurs-given-string/
1090
Chapter 147
1. Append the same elements(i.e. whole array) with the given array.
2. For every window of size n(no. of elements in the given array), perform LIS.
3. Return maximum length.
1091
Chapter 147. Find the Longest Increasing Subsequence in Circular manner
As in the last window we will have the same elements as in the given array which we
don’t need to compute again, so we can append only n-1 elements to reduce the number of
operations.
C++
1092
Chapter 147. Find the Longest Increasing Subsequence in Circular manner
Java
1093
Chapter 147. Find the Longest Increasing Subsequence in Circular manner
C#
// C# implementation to find
// LIS in circular way
using System;
class Test
{
1094
Chapter 147. Find the Longest Increasing Subsequence in Circular manner
1095
Chapter 147. Find the Longest Increasing Subsequence in Circular manner
return res;
}
// Driver method
public static void Main()
{
int []arr = {1, 4, 6, 2, 3};
Console.Write("Length of LICS is " +
LICS( arr, arr.Length));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP implementation to
// find LIS in circular way
// Utility function to find
// LIS using Dynamic programming
function computeLIS($circBuff,
$start,
$end, $n)
{
$LIS = Array();
/* Initialize LIS values
for all indexes */
for ($i = $start; $i < $end; $i++)
$LIS[$i] = 1;
/* Compute optimized LIS
values in bottom up manner */
for ($i = $start + 1; $i < $end; $i++)
// Set j on the basis of
// current window
// i.e. first element of
// the current window
for ( $j = $start; $j < $i; $j++ )
if ($circBuff[$i] > $circBuff[$j] &&
$LIS[$i] < $LIS[$j] + 1)
$LIS[$i] = $LIS[$j] + 1;
/* Pick maximum of
all LIS values */
1096
Chapter 147. Find the Longest Increasing Subsequence in Circular manner
$res = PHP_INT_MIN;
for ($i = $start; $i < $end; $i++)
$res = max($res, $LIS[$i]);
return $res;
}
// Function to find LIS
// in Circular manner
function LICS($arr, $n)
{
// Make a copy of given array
// by appending same array
// elements to itself
for ($i = 0; $i < $n; $i++)
$circBuff[$i] = $arr[$i];
for ($i = $n; $i < 2 * $n; $i++)
$circBuff[$i] = $arr[$i - $n];
// Perform LIS for each
// window of size n
$res = PHP_INT_MIN;
for ($i = 0; $i < $n; $i++)
$res = max(computeLIS($circBuff, $i,
$i + $n, $n),
$res);
return $res;
}
// Driver Code
$arr = array(1, 4, 6, 2, 3);
$n = sizeof($arr);
echo "Length of LICS is " ,
LICS($arr, $n);
// This code is contributed by aj_36
?>
Output :
Length of LICS is 4
Time complexity of above solution is O(n3 ). It can be reduced O(n2 Log n) using O(n Log
n) algorithm to find LIS.
1097
Chapter 147. Find the Longest Increasing Subsequence in Circular manner
Reference :
https://www.careercup.com/question?id=5942735794077696
Improved By : nitin mittal, jit_t
Source
https://www.geeksforgeeks.org/find-longest-increasing-subsequence-circular-manner/
1098
Chapter 148
Find the largest area rectangular sub-matrix whose sum is equal to k - GeeksforGeeks
Given a 2D matrix mat[][] and a value k. Find the largest rectangular sub-matrix whose
sum is equal to k.
Example:
Naive Approach: Check every possible rectangle in given 2D array having sum equal to
‘k’ and print the largest one. This solution requires 4 nested loops and time complexity of
this solution would be O(n^4).
Efficient Approach: Longest sub-array having sum k for 1-D array can be used to reduce
the time complexity to O(n^3). The idea is to fix the left and right columns one by one
and find the longest sub-array having sum equal to ‘k’ for contiguous rows for every left and
right column pair. We basically find top and bottom row numbers (which are part of the
1099
Chapter 148. Find the largest area rectangular sub-matrix whose sum is equal to k
largest sub-matrix) for every fixed left and right column pair. To find the top and bottom
row numbers, calculate sum of elements in every row from left to right and store these sums
in an array say temp[]. So temp[i] indicates sum of elements from left to right in row i.
Now, apply Longest sub-array having sum k 1D algorithm on temp[], and get the longest
sub-array having sum equal to ‘k’ of temp[]. This length would be the maximum possible
length with left and right as boundary columns. Set the ‘top’ and ‘bottom’ row indexes for
the left right column pair and calculate the area. In similar manner get the top, bottom,
left, right indexes for other sub-matrices having sum equal to ‘k’ and print the one having
maximum area.
1100
Chapter 148. Find the largest area rectangular sub-matrix whose sum is equal to k
// check if 'sum-k' is present in 'um'
// or not
if (um.find(sum - k) != um.end()) {
// update maxLength and start and end points
if (maxLen < (i - um[sum - k])) {
maxLen = i - um[sum - k];
start = um[sum - k] + 1;
end = i;
}
}
}
// Return true if maximum length is non-zero
return (maxLen != 0);
}
// function to find the largest area rectangular
// sub-matrix whose sum is equal to k
void sumZeroMatrix(int mat[][MAX], int row, int col, int k)
{
// Variables to store the temporary values
int temp[row], area;
bool sum;
int up, down;
// Variables to store the final output
int fup = 0, fdown = 0, fleft = 0, fright = 0;
int maxArea = INT_MIN;
// Set the left column
for (int left = 0; left < col; left++) {
// Initialize all elements of temp as 0
memset(temp, 0, sizeof(temp));
// Set the right column for the left column
// set by outer loop
for (int right = left; right < col; right++) {
// Calculate sum between current left
// and right column for every row 'i'
for (int i = 0; i < row; i++)
temp[i] += mat[i][right];
// Find largest subarray with 'k' sum in
// temp[]. The sumEqualToK() function also
// sets values of 'up' and 'down;'. So
// if 'sum' is true then rectangle exists between
1101
Chapter 148. Find the largest area rectangular sub-matrix whose sum is equal to k
1102
Chapter 148. Find the largest area rectangular sub-matrix whose sum is equal to k
int main()
{
int mat[][MAX] = { { 1, 7, -6, 5 },
{ -8, 6, 7, -2 },
{ 10, -15, 3, 2 },
{ -5, 2, 0, 9 } };
int row = 4, col = 4;
int k = 7;
sumZeroMatrix(mat, row, col, k);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-the-largest-area-rectangular-sub-matrix-whose-sum-is-equal-to-k/
1103
Chapter 149
The idea is simple, we calculate longest path beginning with every cell. Once we have
computed longest for all cells, we return maximum of all longest paths. One important
observation in this approach is many overlapping subproblems. Therefore this problem can
be optimally solved using Dynamic Programming.
Below is Dynamic Programming based implementation that uses a lookup table dp[][] to
check if a problem is already solved or not.
C/C++
#include<bits/stdc++.h>
#define n 3
using namespace std;
1104
Chapter 149. Find the longest path in a matrix with given constraints
// Returns length of the longest path beginning with mat[i][j].
// This function mainly uses lookup table dp[n][n]
int findLongestFromACell(int i, int j, int mat[n][n], int dp[n][n])
{
// Base case
if (i<0 || i>=n || j<0 || j>=n)
return 0;
// If this subproblem is already solved
if (dp[i][j] != -1)
return dp[i][j];
// Since all numbers are unique and in range from 1 to n*n,
// there is atmost one possible direction from any cell
if (j<n-1 && ((mat[i][j] +1) == mat[i][j+1]))
return dp[i][j] = 1 + findLongestFromACell(i,j+1,mat,dp);
if (j>0 && (mat[i][j] +1 == mat[i][j-1]))
return dp[i][j] = 1 + findLongestFromACell(i,j-1,mat,dp);
if (i>0 && (mat[i][j] +1 == mat[i-1][j]))
return dp[i][j] = 1 + findLongestFromACell(i-1,j,mat,dp);
if (i<n-1 && (mat[i][j] +1 == mat[i+1][j]))
return dp[i][j] = 1 + findLongestFromACell(i+1,j,mat,dp);
// If none of the adjacent fours is one greater
return dp[i][j] = 1;
}
// Returns length of the longest path beginning with any cell
int finLongestOverAll(int mat[n][n])
{
int result = 1; // Initialize result
// Create a lookup table and fill all entries in it as -1
int dp[n][n];
memset(dp, -1, sizeof dp);
// Compute longest path beginning from all cells
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (dp[i][j] == -1)
findLongestFromACell(i, j, mat, dp);
1105
Chapter 149. Find the longest path in a matrix with given constraints
Java
1106
Chapter 149. Find the longest path in a matrix with given constraints
if (i>0 && (mat[i][j] +1 == mat[i-1][j]))
return dp[i][j] = 1 + findLongestFromACell(i-1,j,mat,dp);
if (i<n-1 && (mat[i][j] +1 == mat[i+1][j]))
return dp[i][j] = 1 + findLongestFromACell(i+1,j,mat,dp);
// If none of the adjacent fours is one greater
return dp[i][j] = 1;
}
// Function that returns length of the longest path
// beginning with any cell
static int finLongestOverAll(int mat[][])
{
// Initialize result
int result = 1;
// Create a lookup table and fill all entries in it as -1
int[][] dp = new int[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
dp[i][j] = -1;
// Compute longest path beginning from all cells
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (dp[i][j] == -1)
findLongestFromACell(i, j, mat, dp);
// Update result if needed
result = Math.max(result, dp[i][j]);
}
}
return result;
}
// driver program
public static void main (String[] args)
{
int mat[][] = { {1, 2, 9},
{5, 3, 8},
{4, 6, 7} };
System.out.println("Length of the longest path is " +
finLongestOverAll(mat));
1107
Chapter 149. Find the longest path in a matrix with given constraints
}
}
// Contributed by Pramod Kumar
Output:
Time complexity of the above solution is O(n2 ). It may seem more at first look. If we take
a closer look, we can notice that all values of dp[i][j] are computed only once.
This article is contributed by Ekta Goel. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-the-longest-path-in-a-matrix-with-given-constraints/
1108
Chapter 150
Input:
cost[N][N] = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0}
};
There are 4 stations and cost[i][j] indicates cost to reach j
from i. The entries where j < i are meaningless.
Output:
The minimum cost is 65
The minimum cost can be obtained by first going to station 1
from 0. Then from station 1 to station 3.
We strongly recommend to minimize your browser and try this yourself first.
The minimum cost to reach N-1 from 0 can be recursively written as following:
1109
Chapter 150. Find the minimum cost to reach destination using a train
1110
Chapter 150. Find the minimum cost to reach destination using a train
{
return minCostRec(cost, 0, N-1);
}
// Driver program to test above function
int main()
{
int cost[N][N] = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0}
};
cout << "The Minimum cost to reach station "
<< N << " is " << minCost(cost);
return 0;
}
Java
1111
Chapter 150. Find the minimum cost to reach destination using a train
// This function returns the smallest possible cost to
// reach station N-1 from station 0. This function mainly
// uses minCostRec().
static int minCost(int cost[][])
{
return minCostRec(cost, 0, N-1);
}
public static void main(String args[])
{
int cost[][] = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0}
};
System.out.println("The Minimum cost to reach station "+ N+
" is "+minCost(cost));
}
}/* This code is contributed by Rajat Mishra */
Python
1112
Chapter 150. Find the minimum cost to reach destination using a train
]
print "The Minimum cost to reach station %d is %d" % \
(N, minCost(cost))
# This code is contributed by Divyanshu Mehta
C#
1113
Chapter 150. Find the minimum cost to reach destination using a train
Output:
Time complexity of the above implementation is exponential as it tries every possible path
from 0 to N-1. The above solution solves same subrpoblems multiple times (it can be seen
by drawing recursion tree for minCostPathRec(0, 5).
Since this problem has both properties of dynamic programming problems ((see thisand
this). Like other typical Dynamic Programming(DP) problems, re-computations of same
subproblems can be avoided by storing the solutions to subproblems and solving problems
in bottom up manner.
One dynamic programming solution is to create a 2D table and fill the table using above
given recursive formula. The extra space required in this solution would be O(N2 ) and time
complexity would be O(N3 )
We can solve this problem using O(N) extra space and O(N2 ) time. The idea is based on
the fact that given input matrix is a Directed Acyclic Graph (DAG). The shortest path in
DAG can be calculated using the approach discussed in below post.
Shortest Path in Directed Acyclic Graph
We need to do less work here compared to above mentioned post as we know topological
sorting of the graph. The topological sorting of vertices here is 0, 1, ..., N-1. Following is
the idea once topological sorting is known.
The idea in below code is to first calculate min cost for station 1, then for station 2, and so
on. These costs are stored in an array dist[0...N-1].
1114
Chapter 150. Find the minimum cost to reach destination using a train
C++
1115
Chapter 150. Find the minimum cost to reach destination using a train
int main()
{
int cost[N][N] = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0}
};
cout << "The Minimum cost to reach station "
<< N << " is " << minCost(cost);
return 0;
}
Java
1116
Chapter 150. Find the minimum cost to reach destination using a train
Python3
1117
Chapter 150. Find the minimum cost to reach destination using a train
C#
1118
Chapter 150. Find the minimum cost to reach destination using a train
return dist[N-1];
}
public static void Main()
{
int [,]cost = { {0, 15, 80, 90},
{INF, 0, 40, 50},
{INF, INF, 0, 70},
{INF, INF, INF, 0} };
Console.WriteLine("The Minimum cost to"
+ " reach station "+ N
+ " is "+minCost(cost));
}
}
// This code is contributed by Sam007.
Output:
This article is contributed by Udit Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Sam007
Source
https://www.geeksforgeeks.org/find-the-minimum-cost-to-reach-a-destination-where-every-station-is-connected-in-
1119
Chapter 151
Find the probability of reaching all points after N moves from point N - GeeksforGeeks
Given N which denotes the initial position of the person on the number line. Also given
L which is the probability of the person of going left. Find the probability of reaching all
points on the number line after N moves from point N. Each move can be either to the left
or to the right.
Examples:
Input: n = 2, l = 0.5
Output: 0.2500 0.0000 0.5000 0.0000 0.2500
The person can reach n-1th position and n+1th position in 2 passes, hence the
probability is 0. The person can reach 0th position by only moving 2 steps
left from index 2, hence the probability of reaching 0th index is 05*0.5=0.25.
Similarly for 2n index, the probability is 0.25.
Input: n = 3, l = 0.1
Output: 0.0010 0.0000 0.0270 0.0000 0.2430 0.0000 0.7290
The person can reach n-1th in three ways, i.e., (llr, lrl, rll) where l denotes left
and r denotes right. Hence the probability of n-1th index is 0.027. Similarly
probabilties for all other points are also calculated.
Approach: Construct an array arr[n+1][2n+1] where each row represents a pass and the
columns represent the points on the line. The maximum a person can move from index N
is to 0th index at left or to 2nth index at right. Initially the probabilities after one pass will
be right for arr[1][n-1] and left for arr[1][n+1]. The n-1 moves which are left will be done,
hence the two possible moves will either be n steps to the right or n steps to the left. So
the recurrence relations for right and left moves for all will be:
1120
Chapter 151. Find the probability of reaching all points after N moves from point N
The summation of probabilities for all possible moves for any index will be stored in arr[n][i].
Below is the implementation of the above approach:
1121
Chapter 151. Find the probability of reaching all points after N moves from point N
{
for (int i = 0; i < arr[0].length; i++) {
System.out.printf("%5.4f ", arr[n][i]);
}
}
// Driver Code
public static void main(String[] args)
{
int n = 2;
double left = 0.5;
printProbabilities(n, left);
}
}
Output:
Source
https://www.geeksforgeeks.org/find-the-probability-of-reaching-all-points-after-n-moves-from-point-n/
1122
Chapter 152
Finding the maximum square sub-matrix with all equal elements - GeeksforGeeks
Given a N x N matrix, determine the maximum K such that K x K is a submatrix with all
equal elements i.e., all the elements in this submatrix must be same.
Constraints:
1 <= N <= 1000
0 <= Ai , j <= 109
Examples:
1123
Chapter 152. Finding the maximum square sub-matrix with all equal elements
trix contains equal elements or not in O(n2 ) time Which makes the total running time of
the algorithm as O(n5 ).
Method II ( Dynamic Programming )
For each cell (i, j), we store the largest value of K such that K x K is a submatrix with all
equal elements and position of (i, j) being the bottom-right most element.
And DPi,j depends upon {DPi-1, j , DPi, j-1 , DPi-1, j-1 }
C++
1124
Chapter 152. Finding the maximum square sub-matrix with all equal elements
{
// Check if adjacent elements are equal
if (a[i][j] == a[i-1][j] &&
a[i][j] == a[i][j-1] &&
a[i][j] == a[i-1][j-1] )
dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]),
dp[i-1][j-1] ) + 1;
// If not equal, then it will form a 1x1
// submatrix
else dp[i][j] = 1;
}
// Update result at each (i,j)
result = max(result, dp[i][j]);
}
}
return result;
}
// Driven Program
int main()
{
int a[Row][Col] = { 2, 2, 3, 3, 4, 4,
5, 5, 7, 7, 7, 4,
1, 2, 7, 7, 7, 4,
4, 4, 7, 7, 7, 4,
5, 5, 5, 1, 2, 7,
8, 7, 9, 4, 4, 4
};
cout << largestKSubmatrix(a) << endl;
return 0;
}
Java
1125
Chapter 152. Finding the maximum square sub-matrix with all equal elements
1126
Chapter 152. Finding the maximum square sub-matrix with all equal elements
C#
1127
Chapter 152. Finding the maximum square sub-matrix with all equal elements
else
{
// Check if adjacent
// elements are equal
if (a[i, j] == a[i - 1, j] &&
a[i, j] == a[i, j - 1] &&
a[i, j] == a[i - 1, j - 1])
{
dp[i, j] = (dp[i - 1, j] > dp[i, j - 1] &&
dp[i - 1, j] > dp[i - 1, j - 1] + 1) ?
dp[i - 1, j] :
(dp[i, j - 1] > dp[i - 1, j] &&
dp[i, j - 1] > dp[i - 1, j - 1] + 1) ?
dp[i, j - 1] :
dp[i - 1, j - 1] + 1;
}
// If not equal, then
// it will form a 1x1
// submatrix
else dp[i, j] = 1;
}
// Update result at each (i,j)
result = result > dp[i, j] ?
result : dp[i, j];
}
}
return result;
}
// Driver Code
public static void Main()
{
int[,] a = {{2, 2, 3, 3, 4, 4},
{5, 5, 7, 7, 7, 4},
{1, 2, 7, 7, 7, 4},
{4, 4, 7, 7, 7, 4},
{5, 5, 5, 1, 2, 7},
{8, 7, 9, 4, 4, 4}};
Console.Write(largestKSubmatrix(a));
}
}
// This code is contributed
// by ChitraNayal
1128
Chapter 152. Finding the maximum square sub-matrix with all equal elements
Python 3
1129
Chapter 152. Finding the maximum square sub-matrix with all equal elements
return result
# Driver Code
a = [[ 2, 2, 3, 3, 4, 4],
[ 5, 5, 7, 7, 7, 4],
[ 1, 2, 7, 7, 7, 4],
[ 4, 4, 7, 7, 7, 4],
[ 5, 5, 5, 1, 2, 7],
[ 8, 7, 9, 4, 4, 4]];
print(largestKSubmatrix(a))
# This code is contributed
# by ChitraNayal
PHP
<?php
// Java program to find maximum
// K such that K x K is a
// submatrix with equal elements.
$Row = 6;
$Col = 6;
// Returns size of the largest
// square sub-matrix with
// all same elements.
function largestKSubmatrix(&$a)
{
global $Row, $Col;
$result = 0;
for ($i = 0 ;
$i < $Row ; $i++)
{
for ($j = 0 ;
$j < $Col ; $j++)
{
// If elements is at
// top row or first
// column, it wont form
// a square matrix's
// bottom-right
if ($i == 0 || $j == 0)
$dp[$i][$j] = 1;
else
{
1130
Chapter 152. Finding the maximum square sub-matrix with all equal elements
Output:
1131
Chapter 152. Finding the maximum square sub-matrix with all equal elements
Source
https://www.geeksforgeeks.org/finding-the-maximum-square-sub-matrix-with-all-equal-elements/
1132
Chapter 153
Input : n = 3
Output : 4
Explanation
{1}, {2}, {3} : all single
{1}, {2,3} : 2 and 3 paired but 1 is single.
{1,2}, {3} : 1 and 2 are paired but 3 is single.
{1,3}, {2} : 1 and 3 are paired but 2 is single.
Note that {1,2} and {2,1} are considered same.
1133
Chapter 153. Friends Pairing Problem
Since above recursive formula has overlapping subproblems, we can solve it using Dynamic
Programming.
C++
Java
1134
Chapter 153. Friends Pairing Problem
Python3
1135
Chapter 153. Friends Pairing Problem
dp[i] = i
else:
dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]
return dp[n]
# Driver code
n = 4
print(countFriendsPairings(n))
# This code is contributed
# by Soumen Ghosh.
C#
1136
Chapter 153. Friends Pairing Problem
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program solution for
// friends pairing problem
// Returns count of ways n people
// can remain single or paired up.
function countFriendsPairings($n)
{
$dp[$n + 1] = 0;
// Filling dp[] in bottom-up
// manner using recursive formula
// explained above.
for ($i = 0; $i <= $n; $i++)
{
if ($i <= 2)
$dp[$i] = $i;
else
$dp[$i] = $dp[$i - 1] +
($i - 1) *
$dp[$i - 2];
}
return $dp[$n];
}
// Driver code
$n = 4;
echo countFriendsPairings($n) ;
// This code is contributed
// by nitin mittal.
?>
Output :
10
1137
Chapter 153. Friends Pairing Problem
Source
https://www.geeksforgeeks.org/friends-pairing-problem/
1138
Chapter 154
N → N/2 ( if N is even)
N → 3N + 1 (if N is odd)
It is conjectured but not yet proven that no matter which positive integer
we start with; we always end up with 1.
For example, 10 → 5 → 16 → 8 → 4 → 2 → 1
A Coding Practice Question on Collatz Sequence
Source
https://www.geeksforgeeks.org/collatz-sequence/
1139
Chapter 155
Input: n = 2
Output:
2
1 1
Input: n = 3
Output:
3
2 1
1 1 1
Note: 2+1 and 1+2 are considered as duplicates.
Input: n = 4
Output:
4
3 1
2 2
2 1 1
1 1 1 1
Solution: We print all partition in sorted order and numbers within a partition are also
printed in sorted order (as shown in the above examples). The idea is to get next partition
1140
Chapter 155. Generate all unique partitions of an integer
using the values in current partition. We store every partition in an array p[]. We initialize
p[] as n where n is the input number. In every iteration. we first print p[] and then update
p[] to store the next partition. So the main problem is to get next partition from a given
partition.
Steps to get next partition from current partition:
We are given current partition in p[] and its size. We need to update p[] to store next
partition. Values in p[] must be sorted in non-increasing order.
1. Find the rightmost non-one value in p[] and store the count of 1’s encountered before
a non-one value in a variable rem_val (It indicates sum of values on right side to be
updated). Let the index of non-one value be k.
2. Decrease the value of p[k] by 1 and increase rem_val by 1. Now there may be two
cases:
• a) If
3. b) Else (This is a interesting case, take initial p[] as {3, 1, 1, 1}, p[k] is decreased
from 3 to 2, rem_val is increased from 3 to 4, the next partition should be {2, 2, 2}).
4. Copy p[k] to next position, increment k and reduce count by p[k] while p[k] is less than
rem_val. Finally, put rem_val at p[k+1] and p[0…k+1] is our new partition. This
step is like dividing rem_val in terms of p[k] (4 is divided in 2’s).
C/C++
1141
Chapter 155. Generate all unique partitions of an integer
while (true)
{
// print current partition
printArray(p, k+1);
// Generate next partition
// Find the rightmost non-one value in p[]. Also, update the
// rem_val so that we know how much value can be accommodated
int rem_val = 0;
while (k >= 0 && p[k] == 1)
{
rem_val += p[k];
k--;
}
// if k < 0, all the values are 1 so there are no more partitions
if (k < 0) return;
// Decrease the p[k] found above and adjust the rem_val
p[k]--;
rem_val++;
// If rem_val is more, then the sorted order is violated. Divide
// rem_val in different values of size p[k] and copy these values at
// different positions after p[k]
while (rem_val > p[k])
{
p[k+1] = p[k];
rem_val = rem_val - p[k];
k++;
}
// Copy rem_val to next position and increment position
p[k+1] = rem_val;
k++;
}
}
// Driver program to test above functions
int main()
{
cout << "All Unique Partitions of 2 \n";
printAllUniqueParts(2);
cout << "\nAll Unique Partitions of 3 \n";
printAllUniqueParts(3);
1142
Chapter 155. Generate all unique partitions of an integer
cout << "\nAll Unique Partitions of 4 \n";
printAllUniqueParts(4);
return 0;
}
Java
1143
Chapter 155. Generate all unique partitions of an integer
// if k < 0, all the values are 1 so there are no more partitions
if (k < 0) return;
// Decrease the p[k] found above and adjust the rem_val
p[k]--;
rem_val++;
// If rem_val is more, then the sorted order is violeted. Divide
// rem_val in differnt values of size p[k] and copy these values at
// different positions after p[k]
while (rem_val > p[k])
{
p[k+1] = p[k];
rem_val = rem_val - p[k];
k++;
}
// Copy rem_val to next position and increment position
p[k+1] = rem_val;
k++;
}
}
// Driver program
public static void main (String[] args)
{
System.out.println("All Unique Partitions of 2");
printAllUniqueParts(2);
System.out.println("All Unique Partitions of 3");
printAllUniqueParts(3);
System.out.println("All Unique Partitions of 4");
printAllUniqueParts(4);
}
}
// Contributed by Pramod Kumar
C#
1144
Chapter 155. Generate all unique partitions of an integer
1145
Chapter 155. Generate all unique partitions of an integer
k--;
}
// if k < 0, all the values are 1 so
// there are no more partitions
if (k < 0)
return;
// Decrease the p[k] found above
// and adjust the rem_val
p[k]--;
rem_val++;
// If rem_val is more, then the sorted
// order is violeted. Divide rem_val in
// differnt values of size p[k] and copy
// these values at different positions
// after p[k]
while (rem_val > p[k])
{
p[k+1] = p[k];
rem_val = rem_val - p[k];
k++;
}
// Copy rem_val to next position and
// increment position
p[k+1] = rem_val;
k++;
}
}
// Driver program
public static void Main ()
{
Console.WriteLine("All Unique Partitions of 2");
printAllUniqueParts(2);
Console.WriteLine("All Unique Partitions of 3");
printAllUniqueParts(3);
Console.WriteLine("All Unique Partitions of 4");
printAllUniqueParts(4);
}
}
// This code is contributed by Sam007.
1146
Chapter 155. Generate all unique partitions of an integer
PHP
<?php
// PHP program to generate
// all unique partitions
// of an integer
// A utility function to
// print an array p[] of
// size 'n'
function printArray( $p, $n)
{
for ($i = 0; $i < $n; $i++)
echo $p[$i] , " ";
echo "\n";
}
function printAllUniqueParts($n)
{
// An array to store
// a partition
$p[$n] = array(0);
// Index of last element
// in a partition
$k = 0;
// Initialize first
// partition as number
// itself
$p[$k] = $n;
// This loop first prints
// current partition, then
// generates next partition.
// The loop stops when the
// current partition has all 1s
while (true)
{
// print current partition
printArray($p, $k + 1);
// Generate next partition
// Find the rightmost non-one
// value in p[]. Also, update
// the rem_val so that we know
// how much value can be accommodated
1147
Chapter 155. Generate all unique partitions of an integer
$rem_val = 0;
while ($k >= 0 && $p[$k] == 1)
{
$rem_val += $p[$k];
$k--;
}
// if k < 0, all the values
// are 1 so there are no
// more partitions
if ($k < 0) return;
// Decrease the p[k] found
// above and adjust the
// rem_val
$p[$k]--;
$rem_val++;
// If rem_val is more, then
// the sorted order is violated.
// Divide rem_val in different
// values of size p[k] and copy
// these values at different
// positions after p[k]
while ($rem_val > $p[$k])
{
$p[$k + 1] = $p[$k];
$rem_val = $rem_val - $p[$k];
$k++;
}
// Copy rem_val to next
// position and increment
// position
$p[$k + 1] = $rem_val;
$k++;
}
}
// Driver Code
echo "All Unique Partitions of 2 \n";
printAllUniqueParts(2);
echo "\nAll Unique Partitions of 3 \n";
printAllUniqueParts(3);
echo "\nAll Unique Partitions of 4 \n";
1148
Chapter 155. Generate all unique partitions of an integer
printAllUniqueParts(4);
// This code is contributed
// by akt_mit
?>
Output:
This article is contributed by Hariprasad NG. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : jit_t
Source
https://www.geeksforgeeks.org/generate-unique-partitions-of-an-integer/
1149
Chapter 156
Input : 1787075866
Output : Yes
There exist more one or more subsequences
divisible by 8. Example subsequences are
176, 16 and 8.
Input : 6673177113
Output : No
No subsequence is divisible by 8.
Input : 3144
Output : Yes
The subsequence 344 is divisible by 8.
Property of the divisibility by eight : number can be divided by eight if and only if its last
three digits form a number that can be divided by eight. Thus, it is enough to test only
numbers that can be obtained from the original one by crossing out and that contain at
most three digits i.e we check all one digits, two digits and three digit number combinations.
1150
Chapter 156. Given a large number, check if a subsequence of digits is divisible by 8
1151
Chapter 156. Given a large number, check if a subsequence of digits is divisible by 8
Java
1152
Chapter 156. Given a large number, check if a subsequence of digits is divisible by 8
}
}
// This code is contributed by Nikita Tiwari.
Python3
# Python 3 program to
# check if a subsequence of digits
# is divisible by 8.
# Function to calculate any
# permutation divisible
# by 8. If such permutation
# exists, the function
# will return that permutation
# else it will return -1
def isSubSeqDivisible(st) :
l = len(st)
arr = [0] * l
# Generating all possible
# permutations and checking
# if any such permutation
# is divisible by 8
for i in range(0, l) :
for j in range(i, l) :
for k in range(j, l) :
if (arr[i] % 8 == 0) :
return True
elif ((arr[i]*10 + arr[j])% 8 == 0 and i != j) :
return True
elif ((arr[i] * 100 + arr[j] * 10 + arr[k]) % 8 == 0 and i != j and j != k and i
return True
return False
# Driver function
st = "3144"
if (isSubSeqDivisible(st)) :
print("Yes")
else :
print("No")
1153
Chapter 156. Given a large number, check if a subsequence of digits is divisible by 8
C#
1154
Chapter 156. Given a large number, check if a subsequence of digits is divisible by 8
{
string str = "3144";
if (isSubSeqDivisible(str))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to check if
// a subsequence of digits
// is divisible by 8.
// Function to calculate any
// permutation divisible
// by 8. If such permutation
// exists, the function
// will return that permutation
// else it will return -1
function isSubSeqDivisible($str)
{
// Generating all possible
// permutations and checking
// if any such permutation
// is divisible by 8
$l = strlen($str);
for ( $i = 0; $i < $l ; $i++)
{
for ($j = $i; $j <$l; $j++)
{
for ($k = $j; $k < $l; $k++)
{
if ($arr[$i] % 8 == 0)
return true;
else if (($arr[$i] * 10 +
$arr[$j]) % 8 == 0 &&
$i != $j)
return true;
else if (($arr[$i] * 100 + $arr[$j] *
1155
Chapter 156. Given a large number, check if a subsequence of digits is divisible by 8
Output :
Yes
value of
For all other numbers, we build on a simple concept that either addition of that digit will
contribute in formation of a number divisible by 8, or it shall be left out.
Note: We also have to keep it in mind that we cannot change the order
Now,
1156
Chapter 156. Given a large number, check if a subsequence of digits is divisible by 8
C++
1157
Chapter 156. Given a large number, check if a subsequence of digits is divisible by 8
}
// Driver function
int main()
{
string str = "3144";
if (isSubSeqDivisible(str))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
1158
Chapter 156. Given a large number, check if a subsequence of digits is divisible by 8
+ arr[i])
% 8])
dp[i][(j * 10 + arr[i]) % 8]
= dp[i - 1][j];
// If we exclude the number from
// our combination
if (dp[i - 1][j] > dp[i][j])
dp[i][j] = dp[i - 1][j];
}
}
for (int i = 1; i <= n; i++) {
// If at dp[i][0], we find value 1/true,
// it shows that the number exists at
// the value of 'i'
if (dp[i][0] == 1)
return true;
}
return false;
}
// Driver function
public static void main(String args[])
{
String str = "3144";
if (isSubSeqDivisible(str))
System.out.println("Yes");
else
System.out.println("No");
}
}
/* This code is contributed by Nikita Tiwari.*/
C#
1159
Chapter 156. Given a large number, check if a subsequence of digits is divisible by 8
1160
Chapter 156. Given a large number, check if a subsequence of digits is divisible by 8
{
string str = "3144";
if (isSubSeqDivisible(str))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m.
Output :
Yes
Using the dynamic approach, our time complexity cuts down to , where 8 is
from which the number should be divisible and n is the length of our input. Therefore, the
overall complexity is .
Improved By : vt_m, jit_t
Source
https://www.geeksforgeeks.org/given-large-number-check-subsequence-digits-divisible-8/
1161
Chapter 157
1162
Chapter 157. Gold Mine Problem
Create a 2-D matrix goldTable[][]) of the same as given matrix mat[][]. If we observe the
question closely, we can notice following.
If we are at the first row or last column, then we are unable to move right-up so just assign
0 otherwise assign the value of goldTable[row-1][col+1] to right_up. If we are at the last
row or last column, then we are unable to move right down so just assign 0 otherwise assign
the value of goldTable[row+1][col+1] to right up.
Now find the maximum of right, right_up, and right_down and then add it with that
mat[row][col]. At last, find the maximum of all rows and first column and return it.
CPP
1163
Chapter 157. Gold Mine Problem
goldTable[row+1][col+1];
// Max gold collected from taking either of the
// above 3 paths
goldTable[row][col] = gold[row][col] +
max(right, max(right_up, right_down));
}
}
// The max amount of gold collected will be the max
// value in first column of all rows
int res = goldTable[0][0];
for (int i=1; i<m; i++)
res = max(res, goldTable[i][0]);
return res;
}
// Driver Code
int main()
{
int gold[MAX][MAX]= { {1, 3, 1, 5},
{2, 2, 4, 1},
{5, 0, 2, 3},
{0, 6, 1, 2}
};
int m = 4, n = 4;
cout << getMaxGold(gold, m, n);
return 0;
}
Java
1164
Chapter 157. Gold Mine Problem
1165
Chapter 157. Gold Mine Problem
return res;
}
//driver code
public static void main(String arg[])
{
int gold[][]= { {1, 3, 1, 5},
{2, 2, 4, 1},
{5, 0, 2, 3},
{0, 6, 1, 2} };
int m = 4, n = 4;
System.out.print(getMaxGold(gold, m, n));
}
}
// This code is contributed by Anant Agarwal.
Python3
1166
Chapter 157. Gold Mine Problem
1167
Chapter 157. Gold Mine Problem
Output:
16
Source
https://www.geeksforgeeks.org/gold-mine-problem/
1168
Chapter 158
Golomb sequence
Examples :
Input : n = 4
Output : 1 2 2 3
Input : n = 6
Output : 1 2 2 3 3 4
1169
Chapter 158. Golomb sequence
#include <bits/stdc++.h>
using namespace std;
// Return the nth element
// of Golomb sequence
int findGolomb(int n)
{
// base case
if (n == 1)
return 1;
// Recursive Step
return 1 + findGolomb(n -
findGolomb(findGolomb(n - 1)));
}
// Print the first n
// term of Golomb Sequence
void printGolomb(int n)
{
// Finding first n
// terms of Golomb Sequence.
for (int i = 1; i <= n; i++)
cout << findGolomb(i) << " ";
}
// Driver Code
int main()
{
int n = 9;
printGolomb(n);
return 0;
}
Java
1170
Chapter 158. Golomb sequence
// Recursive Step
return 1 + findGolomb(n -
findGolomb(findGolomb(n - 1)));
}
// Print the first n term of
// Golomb Sequence
public static void printGolomb(int n)
{
// Finding first n terms of
// Golomb Sequence.
for (int i = 1; i <= n; i++)
System.out.print(findGolomb(i) +
" ");
}
// Driver Code
public static void main (String[] args)
{
int n = 9;
printGolomb(n);
}
}
// This code is conttributed by Akash Singh
Python 3
1171
Chapter 158. Golomb sequence
C#
1172
Chapter 158. Golomb sequence
" ");
}
// Driver Code
public static void Main ()
{
int n = 9;
printGolomb(n);
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP Program to find first
// n terms of Golomb sequence.
// Return the nth element
// of Golomb sequence
function findGolomb($n)
{
// base case
if ($n == 1)
return 1;
// Recursive Step
return 1 + findGolomb($n -
findGolomb(findGolomb($n - 1)));
}
// Print the first n
// term of Golomb Sequence
function printGolomb($n)
{
// Finding first n terms
// of Golomb Sequence.
for ($i = 1; $i <= $n; $i++)
echo findGolomb($i) , " ";
}
// Driver Code
1173
Chapter 158. Golomb sequence
$n = 9;
printGolomb($n);
// This code is contributed by anuj_67.
?>
Output :
1 2 2 3 3 4 4 4 5
C++
1174
Chapter 158. Golomb sequence
Java
C#
1175
Chapter 158. Golomb sequence
PHP
<?php
// PHP Program to find first
// n terms of Golomb sequence.
// Print the first n term
// of Golomb Sequence
function printGolomb($n)
{
// base cases
$dp[1] = 1;
echo $dp[1], " ";
// Finding and printing first
// n terms of Golomb Sequence.
for ($i = 2; $i <= $n; $i++)
1176
Chapter 158. Golomb sequence
{
$dp[$i] = 1 + $dp[$i -
$dp[$dp[$i - 1]]];
echo $dp[$i], " ";
}
}
// Driver Code
$n = 9;
printGolomb($n);
// This code is contributed by ajit.
?>
Output :
1 2 2 3 3 4 4 4 5
Source
https://www.geeksforgeeks.org/golomb-sequence/
1177
Chapter 159
Input : M = 20
x[] = {6, 7, 12, 13, 14}
revenue[] = {5, 6, 5, 3, 1}
t = 5
Output: 10
By placing two billboards at 6 miles and 12
miles will produce the maximum revenue of 10.
Input : M = 15
x[] = {6, 9, 12, 14}
revenue[] = {5, 6, 3, 7}
t = 2
Output : 18
Let maxRev[i], 1 <= i <= M, be the maximum revenue generated from beginning to i miles
on the highway. Now for each mile on the highway, we need to check whether this mile
has the option for any billboard, if not then the maximum revenue generated till that mile
would be same as maximum revenue generated till one mile before. But if that mile has the
option for billboard then we have 2 options:
1178
Chapter 159. Highway Billboard Problem
1. Either we will place the billboard, ignore the billboard in previous t miles, and add the
revenue of the billboard placed.
2. Ignore this billboard. So maxRev[i] = max(maxRev[i-t-1] + revenue[i], maxRev[i-1])
Below is implementation of this approach:
C++
1179
Chapter 159. Highway Billboard Problem
nxtbb++;
}
}
else
maxRev[i] = maxRev[i - 1];
}
return maxRev[m];
}
// Driven Program
int main()
{
int m = 20;
int x[] = {6, 7, 12, 13, 14};
int revenue[] = {5, 6, 5, 3, 1};
int n = sizeof(x)/sizeof(x[0]);
int t = 5;
cout << maxRevenue(m, x, revenue, n, t) << endl;
return 0;
}
PHP
<?php
// PHP program to find
// maximum revenue by
// placing billboard on
// the highway with given
// constraints.
function maxRevenue($m, $x,
$revenue,
$n, $t)
{
// Array to store maximum
// revenue at each miles.
$maxRev = array_fill(0, $m + 1,
false);
// actual minimum distance
// between 2 billboards.
$nxtbb = 0;
for ($i = 1; $i <= $m; $i++)
{
// check if all billboards
// are already placed.
1180
Chapter 159. Highway Billboard Problem
1181
Chapter 159. Highway Billboard Problem
$t = 5;
echo maxRevenue($m, $x,
$revenue, $n, $t);
// This code is contributed by ajit
?>
Output:
10
Source
https://www.geeksforgeeks.org/highway-billboard-problem/
1182
Chapter 160
Hosoya’s Triangle
1183
Chapter 160. Hosoya’s Triangle
Thus, the two outermost diagonals are the Fibonacci numbers, while the numbers on the
middle vertical lines are the squares of the Fibonacci numbers. All the other numbers in the
triangle are the product of two distinct Fibonacci numbers greater than 1. The row sums
are the first convolved Fibonnaci numbers.
Sources : Stackoverflow, Wikipedia
Given a positive integers n. The task is print Hosoya’s triangle of size n.
Examples:
Input : n = 4
Output :
1
1 1
2 1 2
3 2 2 3
Input : n = 5
Output :
1
1 1
2 1 2
3 2 2 3
5 3 4 3 5
C++
1184
Chapter 160. Hosoya’s Triangle
#include <bits/stdc++.h>
using namespace std;
int Hosoya(int n, int m)
{
// Base case
if ((n == 0 && m == 0) ||
(n == 1 && m == 0) ||
(n == 1 && m == 1) ||
(n == 2 && m == 1))
return 1;
// Recursive step
if (n > m)
return Hosoya(n - 1, m)
+ Hosoya(n - 2, m);
else if (m == n)
return Hosoya(n - 1, m - 1)
+ Hosoya(n - 2, m - 2);
else
return 0;
}
// Print the Hosoya triangle of height n.
void printHosoya(int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++)
cout << Hosoya(i, j) << " ";
cout << endl;
}
}
// Driven Program
int main()
{
int n = 5;
printHosoya(n);
return 0;
}
Java
1185
Chapter 160. Hosoya’s Triangle
import java.util.*;
class GFG {
static int Hosoya(int n, int m)
{
// Base case
if ((n == 0 && m == 0) ||
(n == 1 && m == 0) ||
(n == 1 && m == 1) ||
(n == 2 && m == 1))
return 1;
// Recursive step
if (n > m)
return Hosoya(n - 1, m)
+ Hosoya(n - 2, m);
else if (m == n)
return Hosoya(n - 1, m - 1)
+ Hosoya(n - 2, m - 2);
else
return 0;
}
// Print the Hosoya triangle of height n.
static void printHosoya(int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= i; j++)
System.out.print(Hosoya(i, j)
+ " ");
System.out.println("");
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
int n = 5;
printHosoya(n);
}
}
1186
Chapter 160. Hosoya’s Triangle
// This code is contributed by Arnav Kr. Mandal.
Python3
C#
1187
Chapter 160. Hosoya’s Triangle
class GFG {
static int Hosoya(int n, int m)
{
// Base case
if ((n == 0 && m == 0) ||
(n == 1 && m == 0) ||
(n == 1 && m == 1) ||
(n == 2 && m == 1))
return 1;
// Recursive step
if (n > m)
return Hosoya(n - 1, m)
+ Hosoya(n - 2, m);
else if (m == n)
return Hosoya(n - 1, m - 1)
+ Hosoya(n - 2, m - 2);
else
return 0;
}
// Print the Hosoya triangle of height n.
static void printHosoya(int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= i; j++)
Console.Write(Hosoya(i, j)
+ " ");
Console.WriteLine("");
}
}
/* Driver program to test above function */
public static void Main()
{
int n = 5;
printHosoya(n);
}
}
1188
Chapter 160. Hosoya’s Triangle
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to print Hosoya's
// triangle of height n.
function Hosoya(int $n, int $m)
{
// Base case
if (($n == 0 && $m == 0) ||
($n == 1 && $m == 0) ||
($n == 1 && $m == 1) ||
($n == 2 && $m == 1))
return 1;
// Recursive step
if ($n > $m)
return Hosoya($n - 1,$m) +
Hosoya($n - 2, $m);
else if ($m == $n)
return Hosoya($n - 1, $m - 1) +
Hosoya($n - 2, $m - 2);
else
return 0;
}
// Print the Hosoya
// triangle of height n.
function printHosoya( $n)
{
for ( $i = 0; $i < $n; $i++)
{
for ( $j = 0; $j <= $i; $j++)
echo Hosoya($i, $j) , " ";
echo "\n";
}
}
// Driven Code
$n = 5;
printHosoya($n);
// This code is contributed by anuj_67.
1189
Chapter 160. Hosoya’s Triangle
?>
Output :
1
1 1
2 1 2
3 2 2 3
5 3 4 3 5
C++
1190
Chapter 160. Hosoya’s Triangle
Java
1191
Chapter 160. Hosoya’s Triangle
}
}
// printing the solution
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= i; j++)
System.out.print(dp[i][j] + " ");
System.out.println("");
}
}
/* Driver program*/
public static void main(String[] args)
{
int n = 5;
printHosoya(n);
}
}
// This code is contributed by Arnav Kr. Mandal.
C#
1192
Chapter 160. Hosoya’s Triangle
Output :
1
1 1
2 1 2
3 2 2 3
5 3 4 3 5
Improved By : vt_m
Source
https://www.geeksforgeeks.org/hosoyas-triangle/
1193
Chapter 161
How to print maximum number of A’s using given four keys - GeeksforGeeks
This is a famous interview question asked in Google, Paytm and many other company
interviews.
Below is the problem statement.
If you can only press the keyboard for N times (with the above four
keys), write a program to produce maximum numbers of A's. That is to
say, the input parameter is N (No. of keys that you can press), the
output is M (No. of As that you can produce).
Examples:
Input: N = 3
Output: 3
We can at most get 3 A's on screen by pressing
following key sequence.
A, A, A
1194
Chapter 161. How to print maximum number of A’s using given four keys
Input: N = 7
Output: 9
We can at most get 9 A's on screen by pressing
following key sequence.
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
Input: N = 11
Output: 27
We can at most get 27 A's on screen by pressing
following key sequence.
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V, Ctrl A,
Ctrl C, Ctrl V, Ctrl V
1195
Chapter 161. How to print maximum number of A’s using given four keys
Java
1196
Chapter 161. How to print maximum number of A’s using given four keys
C#
/* A recursive C# program
to print maximum number
of A's using following
four keys */
using System;
class GFG
{
// A recursive function that
// returns the optimal length
1197
Chapter 161. How to print maximum number of A’s using given four keys
1198
Chapter 161. How to print maximum number of A’s using given four keys
// This code is contributed by Sam007
Output:
The above function computes the same subproblems again and again. Recomputations
of same subproblems can be avoided by storing the solutions to subproblems and solving
problems in bottom up manner.
Below is Dynamic Programming based C implementation where an auxiliary array screen[N]
is used to store result of subproblems.
1199
Chapter 161. How to print maximum number of A’s using given four keys
Java
1200
Chapter 161. How to print maximum number of A’s using given four keys
1201
Chapter 161. How to print maximum number of A’s using given four keys
// (n-b-1)*screen[b-1];
int curr = (n - b - 1) * screen[b - 1];
if (curr > screen[n - 1])
screen[n - 1] = curr;
}
}
return screen[N - 1];
}
// Driver program
public static void main(String [] args)
{
int N;
// for the rest of the array we will rely on the previous
// entries to compute new ones
for (N = 1; N <= 20; N++)
System.out.println("Maximum Number of A's with keystrokes is "+
N + findoptimal(N));
}
}
// This article is contributed by vt_m.
Output:
1202
Chapter 161. How to print maximum number of A’s using given four keys
Thanks to Gaurav Saxena for providing the above approach to solve this problem.
Improved By : Sam007
Source
https://www.geeksforgeeks.org/how-to-print-maximum-number-of-a-using-given-four-keys/
1203
Chapter 162
1. Overlapping Subproblems
2. Optimal Substructure Property
Steps to solve a DP
1) Identify if it is a DP problem
2) Decide a state expression with
least parameters
3) Formulate state relationship
4) Do tabulation (or add memoization)
• Typically, all the problems that require to maximize or minimize certain quantity
or counting problems that say to count the arrangements under certain condition or
certain probability problems can be solved by using Dynamic Programming.
• All dynamic programming problems satisfy the overlapping subproblems property and
most of the classic dynamic problems also satisfy the optimal substructure property.
Once, we observe these properties in a given problem, be sure that it can be solved
using DP.
1204
Chapter 162. How to solve a Dynamic Programming Problem ?
be done very carefully because the state transition depends on the choice of state definition
you make. So, let’s see what do we mean by the term “state”.
State A state can be defined as the set of parameters that can uniquely identify a certain
position or standing in the given problem. This set of parameters should be as small as
possible to reduce state space.
For example: In our famous Knapsack problem, we define our state by two parameters
index and weight i.e DP[index][weight]. Here DP[index][weight] tells us the maximum
profit it can make by taking items from range 0 to index having the capacity of sack to be
weight. Therefore, here the parameters index and weight together can uniquely identify a
subproblem for the knapsack problem.
So, our first step will be deciding a state for the problem after identifying that the problem
is a DP problem.
As we know DP is all about using calculated results to formulate the final result.
So, our next step will be to find a relation between previous states to reach the current state.
Let’s think dynamically about this problem. So, first of all, we decide a state for the
given problem. We will take a parameter n to decide state as it can uniquely identify any
subproblem. So, our state dp will look like state(n). Here, state(n) means the total number
of arrangements to form n by using {1, 3, 5} as elements.
Now, we need to compute state(n).
How to do it?
So here the intuition comes into action. As we can only use 1, 3 or 5 to form a given number.
Let us assume that we know the result for n = 1,2,3,4,5,6 ; being termilogistic let us say we
1205
Chapter 162. How to solve a Dynamic Programming Problem ?
The above code seems exponential as it is calculating the same state again and again. So,
1206
Chapter 162. How to solve a Dynamic Programming Problem ?
// initialize to -1
int dp[MAXN];
// this function returns the number of
// arrangements to form 'n'
int solve(int n)
{
// base case
if (n < 0)
return 0;
if (n == 0)
return 1;
// checking if already calculated
if (dp[n]!=-1)
return dp[n];
// storing the result and returning
return dp[n] = solve(n-1) + solve(n-3) + solve(n-5);
}
Another way is to add tabulation and make solution iterative. Please refer tabulation and
memoization for more details.
Dynamic Programming comes with a lots of practice. One must try solving various classic
DP problems that can be found here. You may check the below problems first and try
solving them using the above described steps:-
• http://www.spoj.com/problems/COINS/
• http://www.spoj.com/problems/ACODE/
• https://www.geeksforgeeks.org/dynamic-programming-set-6-min-cost-path/
• https://www.geeksforgeeks.org/dynamic-programming-subset-sum-problem/
• https://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/
• https://www.geeksforgeeks.org/dynamic-programming-set-5-edit-distance/
Source
https://www.geeksforgeeks.org/solve-dynamic-programming-problem/
1207
Chapter 163
Jacobsthal and
Jacobsthal-Lucas numbers
Jacobsthal-Lucas numbers
Jacobsthal-Lucas numbers represent the complementary Lucas sequence Vn (1, -2). They
satisfy the same recurrence relation as Jacobsthal numbers but have different initial
values:
Given a positive integer n. The task is to find nth Jacobsthal and Jacobsthal-Lucas numbers.
Examples :
1208
Chapter 163. Jacobsthal and Jacobsthal-Lucas numbers
Input : n = 5
Output :
Jacobsthal number: 11
Jacobsthal-Lucas number: 31
Input : n = 4
Output :
Jacobsthal number: 5
Jacobsthal-Lucas number: 17
Below is the implementation of finding nth Jacobsthal and Jacobsthal-Lucas numbers using
recursion.
C++
1209
Chapter 163. Jacobsthal and Jacobsthal-Lucas numbers
return Jacobsthal_Lucas(n - 1) +
2 * Jacobsthal_Lucas(n - 2);
}
// Driven Program
int main()
{
int n = 5;
cout << "Jacobsthal number: " << Jacobsthal(n) << endl;
cout << "Jacobsthal-Lucas number: " << Jacobsthal_Lucas(n) << endl;
return 0;
}
Java
1210
Chapter 163. Jacobsthal and Jacobsthal-Lucas numbers
// recursive step.
return Jacobsthal_Lucas(n - 1) +
2 * Jacobsthal_Lucas(n - 2);
}
// Driver function
public static void main(String argc[]){
int n = 5;
System.out.println("Jacobsthal number: "
+ Jacobsthal(n));
System.out.println("Jacobsthal-Lucas number: "
+ Jacobsthal_Lucas(n));
}
}
/* This code is cotributed Sagar Shukla */
Python3
1211
Chapter 163. Jacobsthal and Jacobsthal-Lucas numbers
C#
1212
Chapter 163. Jacobsthal and Jacobsthal-Lucas numbers
int n = 5;
Console.WriteLine("Jacobsthal number: "
+ Jacobsthal(n));
Console.WriteLine("Jacobsthal-Lucas number: "
+ Jacobsthal_Lucas(n));
}
}
// This code is cotributed vt_m
PHP
<?php
// A simple PHP recursive solution
// to find Jacobsthal and
// Jacobsthal-Lucas numbers
// Return nth Jacobsthal number.
function Jacobsthal($n)
{
// base case
if ($n == 0)
return 0;
// base case
if ($n == 1)
return 1;
// recursive step.
return Jacobsthal($n - 1) +
2 * Jacobsthal($n - 2);
}
// Return nth Jacobsthal-
// Lucas number.
function Jacobsthal_Lucas($n)
{
// base case
if ($n == 0)
return 2;
// base case
if ($n == 1)
return 1;
// recursive step.
return Jacobsthal_Lucas($n - 1) +
2 * Jacobsthal_Lucas($n - 2);
1213
Chapter 163. Jacobsthal and Jacobsthal-Lucas numbers
}
// Driven Code
$n = 5;
echo "Jacobsthal number: " ,
Jacobsthal($n) , "\n";
echo "Jacobsthal-Lucas number: ",
Jacobsthal_Lucas($n), "\n";
// This code is contributed by aj_36
?>
Output :
Jacobsthal number: 11
Jacobsthal-Lucas number: 31
Below is the implementation of finding nth Jacobsthal and Jacobsthal-Lucas numbers using
Dynamic Programming.
C++
1214
Chapter 163. Jacobsthal and Jacobsthal-Lucas numbers
Java
// A DP based solution
// to find Jacobsthal and
// Jacobsthal-Lucas numbers
import java.util.*;
import java.lang.*;
public class GfG{
// Return nth Jacobsthal number.
public static int Jacobsthal(int n)
{
int[] dp = new int[n + 1];
// base case
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++)
dp[i] = dp[i - 1] + 2 * dp[i - 2];
return dp[n];
}
// Return nth Jacobsthal-Lucas number.
public static int Jacobsthal_Lucas(int n)
{
int[] dp = new int[n + 1];
1215
Chapter 163. Jacobsthal and Jacobsthal-Lucas numbers
Python3
1216
Chapter 163. Jacobsthal and Jacobsthal-Lucas numbers
# base case
dp[0] = 2
dp[1] = 1
for i in range(2, n+1):
dp[i] = dp[i - 1] + 2 * dp[i - 2];
return dp[n]
# Driven Program
n = 5
print("Jacobsthal number:",Jacobsthal(n))
print("Jacobsthal-Lucas number:",Jacobsthal_Lucas(n))
# This code is contributed by Smitha Dinesh Semwal
C#
// A DP based solution
// to find Jacobsthal and
// Jacobsthal-Lucas numbers
using System;
public class GfG {
// Return nth Jacobsthal number.
public static int Jacobsthal(int n)
{
int[] dp = new int[n + 1];
// base case
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++)
dp[i] = dp[i - 1] + 2 * dp[i - 2];
return dp[n];
}
// Return nth Jacobsthal-Lucas number.
public static int Jacobsthal_Lucas(int n)
{
int[] dp = new int[n + 1];
// base case
1217
Chapter 163. Jacobsthal and Jacobsthal-Lucas numbers
dp[0] = 2;
dp[1] = 1;
for (int i = 2; i <= n; i++)
dp[i] = dp[i - 1] + 2 * dp[i - 2];
return dp[n];
}
// Driver Code
public static void Main() {
int n = 5;
Console.WriteLine("Jacobsthal number: "
+ Jacobsthal(n));
Console.WriteLine("Jacobsthal-Lucas number: "
+ Jacobsthal_Lucas(n));
}
}
// This code is cotributed vt_m
PHP
<?php
// A DP based solution to
// find Jacobsthal and
// Jacobsthal-Lucas numbers
// Return nth Jacobsthal number.
function Jacobsthal($n)
{
//$dp[$n + 1];
// base case
$dp[0] = 0;
$dp[1] = 1;
for ($i = 2; $i <= $n; $i++)
$dp[$i] = $dp[$i - 1] + 2 *
$dp[$i - 2];
return $dp[$n];
}
// Return nth Jacobsthal-
// Lucas number.
function Jacobsthal_Lucas($n)
1218
Chapter 163. Jacobsthal and Jacobsthal-Lucas numbers
{
// $dp[$n + 1];
// base case
$dp[0] = 2;
$dp[1] = 1;
for ($i = 2; $i <= $n; $i++)
$dp[$i] = $dp[$i - 1] + 2 *
$dp[$i - 2];
return $dp[$n];
}
// Driver Code
$n = 5;
echo "Jacobsthal number: " ,
Jacobsthal($n), "\n";
echo "Jacobsthal-Lucas number: " ,
Jacobsthal_Lucas($n), "\n";
// This code is contributed by ajit
?>
Output:
Jacobsthal number: 11
Jacobsthal-Lucas number: 31
Improved By : jit_t
Source
https://www.geeksforgeeks.org/jacobsthal-and-jacobsthal-lucas-numbers/
1219
Chapter 164
K maximum sums of
non-overlapping contiguous
sub-arrays
Examples:
1220
Chapter 164. K maximum sums of non-overlapping contiguous sub-arrays
k = 2.
Output : Maximum non-overlapping sub-array sum1: 8,
starting index: 0, ending index: 2.
• Find out the maximum subarray in the array using Kadane’s algorithm. Also find out
its starting and end indices. Print the sum of this subarray.
• Fill each cell of this subarray by -infinity.
• Repeat process 1 and 2 for k times.
C++
1221
Chapter 164. K maximum sums of non-overlapping contiguous sub-arrays
Java
1222
Chapter 164. K maximum sums of non-overlapping contiguous sub-arrays
1223
Chapter 164. K maximum sums of non-overlapping contiguous sub-arrays
}
// Driver Program
public static void main(String[] args)
{
// Test case 1
int arr1[] = {4, 1, 1, -1, -3, -5,
6, 2, -6, -2};
int k1 = 3;
int n1 = arr1.length;
// Function calling
kmax(arr1, k1, n1);
// Test case 2
int arr2[] = {5, 1, 2, -6, 2, -1, 3, 1};
int k2 = 2;
int n2 = arr2.length;
// Function calling
kmax(arr2, k2, n2);
}
}
// This code is contributed by Nirmal Patel
Python3
1224
Chapter 164. K maximum sums of non-overlapping contiguous sub-arrays
for i in range(n):
max_here += arr[i]
if (max_so_far < max_here):
max_so_far = max_here
start = s
end = i
if (max_here < 0):
max_here = 0
s = i + 1
# Print out the result
print("Maximum non-overlapping sub-array sum",
c + 1, ": ", max_so_far, ", starting index: ",
start, ", ending index: ", end, ".", sep = "")
# Replace all elements of the maximum subarray
# by -infinity. Hence these places cannot form
# maximum sum subarray again.
for l in range(start, end+1):
arr[l] = -float("inf")
print()
# Driver Program
# Test case 1
arr1 = [4, 1, 1, -1, -3, -5, 6, 2, -6, -2]
k1 = 3
n1 = len(arr1)
# Function calling
kmax(arr1, k1, n1)
# Test case 2
arr2 = [5, 1, 2, -6, 2, -1, 3, 1]
k2 = 2
n2 = len(arr2)
# Function calling
kmax(arr2, k2, n2)
C#
1225
Chapter 164. K maximum sums of non-overlapping contiguous sub-arrays
class GFG {
// Method to compute k
// maximum sub-array sums.
static void kmax(int []arr, int k, int n) {
// In each iteration it will give
// the ith maximum subarray sum.
for(int c = 0; c < k; c++)
{
// Kadane's algorithm.
int max_so_far = int.MinValue;
int max_here = 0;
// compute starting and ending
// index of each of the sub-array.
int start = 0, end = 0, s = 0;
for(int i = 0; i < n; i++)
{
max_here += arr[i];
if (max_so_far < max_here)
{
max_so_far = max_here;
start = s;
end = i;
}
if (max_here < 0)
{
max_here = 0;
s = i + 1;
}
}
// Print out the result.
Console.WriteLine("Maximum non-overlapping sub-arraysum" +
(c + 1) + ": "+ max_so_far +
", starting index: " + start +
", ending index: " + end + ".");
// Replace all elements of the maximum subarray
// by -infinity. Hence these places cannot form
// maximum sum subarray again.
for (int l = start; l <= end; l++)
arr[l] = int.MinValue;
}
Console.WriteLine();
}
1226
Chapter 164. K maximum sums of non-overlapping contiguous sub-arrays
PHP
<?php
// PHP program to find out k maximum
// non-overlapping sub-array sums.
// Method to compute k
// maximum sub-array sums.
function kmax($arr, $k, $n) {
// In each iteration it will give
// the ith maximum subarray sum.
for( $c = 0; $c < $k; $c++)
{
// Kadane's algorithm.
$max_so_far = PHP_INT_MIN;
$max_here = 0;
// compute starting and ending
// index of each of the sub-array.
$start = 0; $end = 0; $s = 0;
for($i = 0; $i < $n; $i++)
{
$max_here += $arr[$i];
1227
Chapter 164. K maximum sums of non-overlapping contiguous sub-arrays
1228
Chapter 164. K maximum sums of non-overlapping contiguous sub-arrays
?>
Output:
Time Complexity: The outer loop runs for k times and kadane’s algorithm in each itera-
tion runs in linear time O(n). Hence the overall time complexity is O(k*n).
Improved By : Nims972, parashar, vt_m
Source
https://www.geeksforgeeks.org/k-maximum-sums-non-overlapping-contiguous-sub-arrays/
1229
Chapter 165
K maximum sums of
overlapping contiguous
sub-arrays
Using Kadane’s Algorithm we can find the maximum contiguous subarray sum of an array.
But in the case Kadane’s Algorithm does not work. As whenever we hit an negative number
in the array we set the max_ending_here variable to zero, hence we miss the possibilities
for second and so on maximums.
Here we is an algorithm presented by Sung Eun Bae and Tadao Takaoka which computes
the maximum sub-array sum problem in O(n) time and k maximum sub-array sum problem
in O(k*n) time.
First we look at the problem of only maximum sub-array sum using this method:
Prerequisite:
1. Prefix sum array
2. Maximum subarray sum in O(n) using prefix sum
1230
Chapter 165. K maximum sums of overlapping contiguous sub-arrays
Throughout this calculation method we keep maxi in non-increasing and mini in non-
decreasing order.
C++
1231
Chapter 165. K maximum sums of overlapping contiguous sub-arrays
1232
Chapter 165. K maximum sums of overlapping contiguous sub-arrays
// Initialize cand array.
vector<int> cand(k);
// For each element of the prefix_sum array do:
// compute the cand array.
// take k maximum values from maxi and cand
// using maxmerge function.
// insert prefix_sum[i] to mini array if needed
// using insertMini function.
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++) {
if(pre_sum[i] < 0 && mini[j]==numeric_limits<int>::max())
cand[j]=(-pre_sum[i])-mini[j];
else cand[j] = pre_sum[i] - mini[j];
}
maxMerge(maxi, cand);
insertMini(mini, pre_sum[i]);
}
// Elements of maxi array is the k
// maximum overlapping sub-array sums.
// Print out the elements of maxi array.
for (int ele : maxi)
cout << ele << " ";
cout << endl;
}
// Driver Program
int main()
{
// Test case 1
vector<int> arr1 = { 4, -8, 9, -4, 1, -8, -1, 6 };
int k1 = 4;
kMaxOvSubArray(arr1, k1);
// Test case 2
vector<int> arr2 = { -2, -3, 4, -1, -2, 1, 5, -3 };
int k2 = 3;
kMaxOvSubArray(arr2, k2);
return 0;
}
Python3
1233
Chapter 165. K maximum sums of overlapping contiguous sub-arrays
1234
Chapter 165. K maximum sums of overlapping contiguous sub-arrays
pre_sum = prefix_sum(arr, n)
# Set all the elements of mini as + infinite
# except 0th. Set the 0th element as 0.
mini = [float('inf') for i in range(k)]
mini[0] = 0
# Set all the elements of maxi as -infinite.
maxi = [-float('inf') for i in range(k)]
# Initialize cand array.
cand = [0 for i in range(k)]
# For each element of the prefix_sum array do:
# compute the cand array.
# take k maximum values from maxi and cand
# using maxmerge function.
# insert prefix_sum[i] to mini array if needed
# using insertMini function.
for i in range(n):
for j in range(k):
cand[j] = pre_sum[i] - mini[j]
maxMerge(maxi, cand)
insertMini(mini, pre_sum[i])
# Elements of maxi array is the k
# maximum overlapping sub-array sums.
# Print out the elements of maxi array.
for ele in maxi:
print(ele, end = ' ')
print('')
# Driver Program
# Test case 1
arr1 = [4, -8, 9, -4, 1, -8, -1, 6]
k1 = 4
kMaxOvSubArray(arr1, k1)
# Test case 2
arr2 = [-2, -3, 4, -1, -2, 1, 5, -3]
k2 = 3
kMaxOvSubArray(arr2, k2)
Output:
9 6 6 5
7 6 5
1235
Chapter 165. K maximum sums of overlapping contiguous sub-arrays
Time Complexity: The ‘insertMini’ and ‘maxMerge’ functions runs in O(k) time and it
takes O(k) time to update the ‘cand’ array. We do this process for n times. Hence, the
overall time complexity is O(k*n).
Improved By : getLost
Source
https://www.geeksforgeeks.org/k-maximum-sum-overlapping-contiguous-sub-arrays/
1236
Chapter 166
1237
Chapter 166. LCS (Longest Common Subsequence) of three strings
1238
Chapter 166. LCS (Longest Common Subsequence) of three strings
else
L[i][j][k] = max(max(L[i-1][j][k],
L[i][j-1][k]),
L[i][j][k-1]);
}
}
}
/* L[m][n][o] contains length of LCS for
X[0..n-1] and Y[0..m-1] and Z[0..o-1]*/
return L[m][n][o];
}
/* Driver program to test above function */
int main()
{
string X = "AGGT12";
string Y = "12TXAYB";
string Z = "12XBA";
int m = X.length();
int n = Y.length();
int o = Z.length();
cout << "Length of LCS is " << lcsOf3(X, Y,
Z, m, n, o);
return 0;
}
Java
1239
Chapter 166. LCS (Longest Common Subsequence) of three strings
{
for (int j=0; j<=n; j++)
{
for (int k=0; k<=o; k++)
{
if (i == 0 || j == 0||k==0)
L[i][j][k] = 0;
else if (X.charAt(i - 1) == Y.charAt(j - 1)
&& X.charAt(i - 1)==Z.charAt(k - 1))
L[i][j][k] = L[i-1][j-1][k-1] + 1;
else
L[i][j][k] = Math.max(Math.max(L[i-1][j][k],
L[i][j-1][k]),
L[i][j][k-1]);
}
}
}
/* L[m][n][o] contains length of LCS for
X[0..n-1] and Y[0..m-1] and Z[0..o-1]*/
return L[m][n][o];
}
/* Driver program to test above function */
public static void main(String args[])
{
String X = "AGGT12";
String Y = "12TXAYB";
String Z = "12XBA";
int m = X.length();
int n = Y.length();
int o = Z.length();
System.out.println("Length of LCS is " +
lcsOf3(X, Y,Z, m, n, o));
}
}
// This code is contributed by Sumit Ghosh
Python3
1240
Chapter 166. LCS (Longest Common Subsequence) of three strings
C#
// C# program to find
1241
Chapter 166. LCS (Longest Common Subsequence) of three strings
1242
Chapter 166. LCS (Longest Common Subsequence) of three strings
PHP
<?php
// PHP program to find
// LCS of three strings
/* Returns length of LCS for
X[0..m-1], Y[0..n-1] and Z[0..o-1] */
function lcsOf3($X, $Y, $Z,
$m, $n, $o)
{
$L[$m + 1][$n + 1][$o + 1] = array(array(array()));
/* Following steps build
L[m+1][n+1][o+1] in bottom
up fashion. Note that
L[i][j][k] contains length
of LCS of X[0..i-1] and
Y[0..j-1] and Z[0.....k-1]*/
for ($i = 0; $i <= $m; $i++)
{
for ($j = 0; $j <= $n; $j++)
{
for ($k = 0; $k <= $o; $k++)
{
1243
Chapter 166. LCS (Longest Common Subsequence) of three strings
Output:
Length of LCS is 2
Source
https://www.geeksforgeeks.org/lcs-longest-common-subsequence-three-strings/
1244
Chapter 167
Input : s1 = aggayxysdfa
s2 = aggajxaaasdfa
k = 4
Output : 8
Explanation: aggasdfa is the longest
subsequence that can be formed by taking
consecutive segments, minimum of length 4.
Here segments are "agga" and "sdfa" which
are of length 4 which is included in making
the longest subsequence.
Input : s1 = aggasdfa
s2 = aggajasdfaxy
k = 5
Output : 5
Input: s1 = "aabcaaaa"
s2 = "baaabcd"
k = 3
Output: 4
Explanation: "aabc" is the longest subsequence that
is formed by taking segment of minimum length 3.
1245
Chapter 167. LCS formed by consecutive segments of at least length K
C++
1246
Chapter 167. LCS formed by consecutive segments of at least length K
Java
1247
Chapter 167. LCS formed by consecutive segments of at least length K
1248
Chapter 167. LCS formed by consecutive segments of at least length K
int k = 4;
String s1 = "aggasdfa";
String s2 = "aggajasdfa";
System.out.println(longestSubsequenceCommonSegment(k, s1, s2));
}
}
// This code is contributed by prerna saini.
C#
1249
Chapter 167. LCS formed by consecutive segments of at least length K
{
// formulate for all length of segments
// to get the longest subsequence with
// consecutive Common Segment of length
// of min k length
for (int a = k; a <= cnt[i,j]; a++)
// update lcs value by adding
// segment length
lcs[i,j] = Math.Max(lcs[i,j],
lcs[i - a,j - a] + a);
}
}
}
return lcs[n,m];
}
// driver code to check the above fucntion
public static void Main()
{
int k = 4;
string s1 = "aggasdfa";
string s2 = "aggajasdfa";
Console.WriteLine(longestSubsequenceCommonSegment(k, s1, s2));
}
}
// This code is contributed by vt_m.
Output:
Source
https://www.geeksforgeeks.org/lcs-formed-consecutive-segments-least-length-k/
1250
Chapter 168
Kadane’s Algorithm:
1251
Chapter 168. Largest Sum Contiguous Subarray
Initialize:
max_so_far = 0
max_ending_here = 0
Explanation:
Simple idea of the Kadane’s algorithm is to look for all positive contiguous segments of the
array (max_ending_here is used for this). And keep track of maximum sum contiguous
segment among all positive segments (max_so_far is used for this). Each time we get a
positive sum compare it with max_so_far and update max_so_far if it is greater than
max_so_far
max_so_far = max_ending_here = 0
1252
Chapter 168. Largest Sum Contiguous Subarray
Program:
C++
1253
Chapter 168. Largest Sum Contiguous Subarray
Java
import java.io.*;
// Java program to print largest contiguous array sum
import java.util.*;
class Kadane
{
public static void main (String[] args)
{
int [] a = {-2, -3, 4, -1, -2, 1, 5, -3};
System.out.println("Maximum contiguous sum is " +
maxSubArraySum(a));
}
static int maxSubArraySum(int a[])
{
int size = a.length;
int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
}
Python
1254
Chapter 168. Largest Sum Contiguous Subarray
if max_ending_here < 0:
max_ending_here = 0
return max_so_far
# Driver function to check the above function
a = [-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7]
print "Maximum contiguous sum is", maxSubArraySum(a,len(a))
#This code is contributed by _Devesh Agrawal_
C#
1255
Chapter 168. Largest Sum Contiguous Subarray
// This code is contributed by Sam007_
PHP
<?php
// PHP program to print largest
// contiguous array sum
function maxSubArraySum($a, $size)
{
$max_so_far = PHP_INT_MIN;
$max_ending_here = 0;
for ($i = 0; $i < $size; $i++)
{
$max_ending_here = $max_ending_here + $a[$i];
if ($max_so_far < $max_ending_here)
$max_so_far = $max_ending_here;
if ($max_ending_here < 0)
$max_ending_here = 0;
}
return $max_so_far;
}
// Driver code
$a = array(-2, -3, 4, -1,
-2, 1, 5, -3);
$n = count($a);
$max_sum = maxSubArraySum($a, $n);
echo "Maximum contiguous sum is " ,
$max_sum;
// This code is contributed by anuj_67.
?>
Output:
C++
1256
Chapter 168. Largest Sum Contiguous Subarray
Python
def maxSubArraySum(a,size):
max_so_far = 0
max_ending_here = 0
for i in range(0, size):
max_ending_here = max_ending_here + a[i]
if max_ending_here < 0:
max_ending_here = 0
# Do not compare for all elements. Compare only
# when max_ending_here > 0
elif (max_so_far < max_ending_here):
max_so_far = max_ending_here
return max_so_far
C++
#include<iostream>
using namespace std;
1257
Chapter 168. Largest Sum Contiguous Subarray
Java
1258
Chapter 168. Largest Sum Contiguous Subarray
int n = a.length;
int max_sum = maxSubArraySum(a, n);
System.out.println("Maximum contiguous sum is "
+ max_sum);
}
}
// This code is contributd by Prerna Saini
Python
C#
1259
Chapter 168. Largest Sum Contiguous Subarray
}
return max_so_far;
}
// Drive code
public static void Main ()
{
int []a = {-2, -3, 4, -1, -2, 1, 5, -3};
int n = a.Length;
Console.Write("Maximum contiguous sum is "
+ maxSubArraySum(a, n));
}
}
// This code is contributed by Sam007_
Output:
To print the subarray with the maximum sum, we maintain indices whenever we get the
maximum sum.
C++
1260
Chapter 168. Largest Sum Contiguous Subarray
if (max_ending_here < 0)
{
max_ending_here = 0;
s = i + 1;
}
}
cout << "Maximum contiguous sum is "
<< max_so_far << endl;
cout << "Starting index "<< start
<< endl << "Ending index "<< end << endl;
}
/*Driver program to test maxSubArraySum*/
int main()
{
int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int n = sizeof(a)/sizeof(a[0]);
int max_sum = maxSubArraySum(a, n);
return 0;
}
Java
1261
Chapter 168. Largest Sum Contiguous Subarray
s = i + 1;
}
}
System.out.println("Maximum contiguous sum is "
+ max_so_far);
System.out.println("Starting index " + start);
System.out.println("Ending index " + end);
}
// Driver code
public static void main(String[] args)
{
int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
int n = a.length;
maxSubArraySum(a, n);
}
}
// This code is contributed by prerna saini
Python3
1262
Chapter 168. Largest Sum Contiguous Subarray
print ("Maximum contiguous sum is %d"%(max_so_far))
print ("Starting Index %d"%(start))
print ("Ending Index %d"%(end))
# Driver program to test maxSubArraySum
a = [-2, -3, 4, -1, -2, 1, 5, -3]
maxSubArraySum(a,len(a))
C#
1263
Chapter 168. Largest Sum Contiguous Subarray
// Driver code
public static void Main()
{
int []a = {-2, -3, 4, -1,
-2, 1, 5, -3};
int n = a.Length;
maxSubArraySum(a, n);
}
}
// This code is contributed
// by anuj_67.
Output:
References:
http://en.wikipedia.org/wiki/Kadane%27s_Algorithm
Improved By : vt_m
Source
https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/
1264
Chapter 169
Largest area rectangular sub-matrix with equal number of 1’s and 0’s - GeeksforGeeks
Given a binary matrix. The problem is to find the largest area rectangular sub-matrix with
equal number of 1’s and 0’s.
Examples:
The naive solution for this problem is to check every possible rectangle in given 2D array
by counting the total number of 1’s and 0’s in that rectangle. This solution requires 4 nested
loops and time complexity of this solution would be O(n^4).
An efficient solution is based on Largest rectangular sub-matrix whose sum is 0 which
reduces the time complexity to O(n^3). First of all consider every ‘0’ in the matrix as ‘-1’.
Now, the idea is to reduce the problem to 1-D array. We fix the left and right columns one
by one and find the largest sub-array with 0 sum contiguous rows for every left and right
1265
Chapter 169. Largest area rectangular sub-matrix with equal number of 1’s and 0’s
column pair. We basically find top and bottom row numbers (which have sum zero) for
every fixed left and right column pair. To find the top and bottom row numbers, calculate
sum of elements in every row from left to right and store these sums in an array say temp[].
So temp[i] indicates sum of elements from left to right in row i. If we find largest subarray
with 0 sum in temp[], we can get the index positions of rectangular sub-matrix with sum
equal to 0 (i.e. having equal number of 1’s and 0’s). With this process we can find the
largest area rectangular sub-matrix with sum equal to 0 (i.e. having equal number of 1’s
and 0’s). We can use Hashing technique to find maximum length sub-array with sum equal
to 0 in 1-D array in O(n) time.
1266
Chapter 169. Largest area rectangular sub-matrix with equal number of 1’s and 0’s
1267
Chapter 169. Largest area rectangular sub-matrix with equal number of 1’s and 0’s
// to store the final outputs
int finalLeft, finalRight, finalTop, finalBottom;
finalLeft = finalRight = finalTop = finalBottom = -1;
int maxArea = 0;
// Set the left column
for (int left = 0; left < col; left++)
{
// Initialize all elements of temp as 0
memset(temp, 0, sizeof(temp));
// Set the right column for the left column
// set by outer loop
for (int right = left; right < col; right++)
{
// Calculate sum between current left
// and right for every row 'i'
// consider value '1' as '1' and
// value '0' as '-1'
for (int i=0; i<row; i++)
temp[i] += mat[i][right] ? 1 : -1;
// Find largest subarray with 0 sum in
// temp[]. The subArrWithSumZero() function
// also sets values of finalTop, finalBottom,
// finalLeft and finalRight if there exists
// a subarray with sum 0 in temp
if (subArrWithSumZero(temp, startRow, endRow, row))
{
int area = (right - left + 1) *
(endRow - startRow + 1);
// Compare current 'area' with previous area
// and accodingly update final values
if (maxArea < area)
{
finalTop = startRow;
finalBottom = endRow;
finalLeft = left;
finalRight = right;
maxArea = area;
}
}
}
}
// if true then there is no rectangular submatrix
1268
Chapter 169. Largest area rectangular sub-matrix with equal number of 1’s and 0’s
Output:
Source
https://www.geeksforgeeks.org/largest-area-rectangular-sub-matrix-equal-number-1s-0s/
1269
Chapter 170
This can be solved using Dynamic Programming. We first sort the array so that the largest
element is at the end. Then we traverse the sorted array from end. For every element
a[i], we compute dp[i] where dp[i] indicates size of largest divisible subset where a[i] is the
smallest element. We can compute dp[i] in a sorted array using values from dp[i+1] to
dp[n-1]. Finally we return maximum value from dp[].
Below is the implementation of the above approach:
C++
1270
Chapter 170. Largest divisible pairs subset
Python3
# Python program to find the largest
# subset where each pair is divisible.
# function to find the longest Subsequence
def largestSubset(a, n):
1271
Chapter 170. Largest divisible pairs subset
# Sort array in
# increasing order
a.sort()
# dp[i] is going to store size
# of largest divisible subset
# beginning with a[i].
dp = [0 for i in range(n)]
# Since last element is largest,
# d[n-1] is 1
dp[n – 1] = 1;
# Fill values for smaller elements
for i in range(n – 2, -1, -1):
# Find all multiples of a[i]
# and consider the multiple
# that has largest subset
# beginning with it.
mxm = 0;
for j in range(i + 1, n):
if a[j] % a[i] == 0:
mxm = max(mxm, dp[j])
dp[i] = 1 + mxm
# Return maximum value from dp[]
return max(dp)
# Driver Code
a = [ 1, 3, 6, 13, 17, 18 ]
n = len(a)
print(largestSubset(a, n))
# This code is contributed by
# sahil shelangia
C#
1272
Chapter 170. Largest divisible pairs subset
// dp[i] is going to store size of largest
// divisible subset beginning with a[i].
int[] dp = new int[n];
// Since last element is largest, d[n-1] is 1
dp[n - 1] = 1;
// Fill values for smaller elements.
for (int i = n - 2; i >= 0; i--) {
// Find all multiples of a[i] and consider
// the multiple that has largest subset
// beginning with it.
int mxm = 0;
for (int j = i + 1; j < n; j++)
if (a[j] % a[i] == 0)
mxm = Math.Max(mxm, dp[j]);
dp[i] = 1 + mxm;
}
// Return maximum value from dp[]
return dp.Max();
}
// driver code to check the above function
static public void Main()
{
int[] a = { 1, 3, 6, 13, 17, 18 };
int n = a.Length;
Console.WriteLine(largestSubset(a, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find the
// largest subset which
// where each pair is
// divisible.
// function to find the
// longest Subsequence
function largestSubset($a, $n)
1273
Chapter 170. Largest divisible pairs subset
{
// Sort array in
// increasing order
sort($a);
// dp[i] is going to
// store size of largest
// divisible subset
// beginning with a[i].
$dp = array();
// Since last element is
// largest, d[n-1] is 1
$dp[$n - 1] = 1;
// Fill values for
// smaller elements.
for ($i = $n - 2; $i >= 0; $i--)
{
// Find all multiples of
// a[i] and consider
// the multiple that
// has largest subset
// beginning with it.
$mxm = 0;
for ($j = $i + 1; $j < $n; $j++)
if ($a[$j] % $a[$i] == 0)
$mxm = max($mxm, $dp[$j]);
$dp[$i] = 1 + $mxm;
}
// Return maximum value
// from dp[]
return max($dp);
}
// Driver Code
$a = array(1, 3, 6, 13, 17, 18);
$n = count($a);
echo largestSubset($a, $n);
// This code is contributed by anuj_67.
?>
Output:
1274
Chapter 170. Largest divisible pairs subset
Source
https://www.geeksforgeeks.org/largest-divisible-pairs-subset/
1275
Chapter 171
k = 5
Output : Area = 12
(Top, Left): (0, 0)
(Bottom, Right): (2, 3)
The sub-matrix is:
| 1, 2, -1, -4 |
| -8, -3, 4, 2 |
| 3, 8, 10, 1 |
Naive Approach: Check every possible rectangle in given 2D array having sum divisible
by ‘k’ and print the largest one. This solution requires 4 nested loops and time complexity
of this solution would be O(n^4).
Efficient Approach: Longest subarray having sum divisible by k for 1-D array can be
used to reduce the time complexity to O(n^3). The idea is to fix the left and right columns
one by one and find the longest sub-array having sum divisible by ‘k’ for contiguous rows
1276
Chapter 171. Largest rectangular sub-matrix having sum divisible by k
for every left and right column pair. We basically find top and bottom row numbers (which
are part of the largest sub-matrix) for every fixed left and right column pair. To find the top
and bottom row numbers, calculate sum of elements in every row from left to right and store
these sums in an array say temp[]. So temp[i] indicates sum of elements from left to right
in row i. Now, apply Longest subarray having sum divisible by k 1D algorithm on temp[],
and get the longest sub-array having sum divisible by ‘k’ of temp[]. This length would be
the maximum possible length with left and right as boundary columns. Set the ‘top’ and
‘bottom’ row indexes for the left right column pair and calculate the area. In similar manner
get the top, bottom, left, right indexes for other sub-matrices having sum divisible by ‘k’
and print the one having maximum area.
1277
Chapter 171. Largest rectangular sub-matrix having sum divisible by k
1278
Chapter 171. Largest rectangular sub-matrix having sum divisible by k
Output:
1279
Chapter 171. Largest rectangular sub-matrix having sum divisible by k
Area: 12
Source
https://www.geeksforgeeks.org/largest-rectangular-sub-matrix-sum-divisible-k/
1280
Chapter 172
Examples:
Input : 1, 2, 3
-3, -2, -1
1, 7, 5
Output : 1, 2, 3
-3, -2, -1
1281
Chapter 172. Largest rectangular sub-matrix whose sum is 0
Input : 9, 7, 16, 5
1, -6, -7, 3
1, 8, 7, 9
7, -2, 0, 10
Output :-6, -7
8, 7
-2, 0
The naive solution for this problem is to check every possible rectangle in given 2D array.
This solution requires 4 nested loops and time complexity of this solution would be O(n^4).
The solution is based onMaximum sum rectangle in a 2D matrix. The idea is to reduce
the problem to 1 D array. We can use Hashing to find maximum length of sub-array in
1-D array in O(n) time. We fix the left and right columns one by one and find the largest
sub-array with 0 sum contiguous rows for every left and right column pair. We basically
find top and bottom row numbers (which have sum is zero) for every fixed left and right
column pair. To find the top and bottom row numbers, calculate sum of elements in every
row from left to right and store these sums in an array say temp[]. So temp[i] indicates sum
of elements from left to right in row i. If we find largest subarray with 0 sum on temp, and
no. of elements is greater than previous no. of elements then update the values of final
row_up, final row_down, final col_left, final col_right.
1282
Chapter 172. Largest rectangular sub-matrix whose sum is 0
{
// Add current element to sum
sum += temp[i];
if (temp[i] == 0 && max_length == 0)
{
*starti = i;
*endj = i;
max_length = 1;
}
if (sum == 0)
{
if (max_length < i + 1)
{
*starti = 0;
*endj = i;
}
max_length = i + 1;
}
// Look for this sum in Hash table
if (presum.find(sum) != presum.end())
{
// store previous max_length so
// that we can check max_length
// is updated or not
int old = max_length;
// If this sum is seen before,
// then update max_len
max_length = max(max_length, i - presum[sum]);
if (old < max_length)
{
// If max_length is updated then
// enter and update start and end
// point of array
*endj = i;
*starti = presum[sum] + 1;
}
}
else
// Else insert this sum with
// index in hash table
presum[sum] = i;
}
1283
Chapter 172. Largest rectangular sub-matrix whose sum is 0
1284
Chapter 172. Largest rectangular sub-matrix whose sum is 0
fdown = down;
fleft = left;
fright = right;
maxl = ele;
}
}
}
// If there is no change in boundaries
// than check if a[0][0] is 0
// If it not zero then print
// that no such zero-sum sub-matrix exists
if (fup == 0 && fdown == 0 && fleft == 0 &&
fright == 0 && a[0][0] != 0) {
cout << "No zero-sum sub-matrix exists";
return;
}
// Print final values
for (int j = fup; j <= fdown; j++)
{
for (int i = fleft; i <= fright; i++)
cout << a[j][i] << " ";
cout << endl;
}
}
// Driver program to test above functions
int main()
{
int a[][MAX] = { { 9, 7, 16, 5 }, { 1, -6, -7, 3 },
{ 1, 8, 7, 9 }, { 7, -2, 0, 10 } };
int row = 4, col = 4;
sumZeroMatrix(a, row, col);
return 0;
}
Output:
-6, -7
8, 7
-2, 0
Source
https://www.geeksforgeeks.org/largest-rectangular-sub-matrix-whose-sum-0/
1285
Chapter 173
Input : mat[][] = 3 1 2
4 8 5
6 9 7
Output : 18
Zigzag sequence is: 3->8->7
Another such sequence is 2->4->7
Input : mat[][] = 4 2 1
3 9 6
11 3 15
Output : 28
1286
Chapter 173. Largest sum Zigzag sequence in a matrix
C++
1287
Chapter 173. Largest sum Zigzag sequence in a matrix
{11, 3, 15}};
cout << "Largest zigzag sum: " << largestZigZag(mat, n);
return 0;
}
Java
1288
Chapter 173. Largest sum Zigzag sequence in a matrix
largestZigZagSumRec(mat, 0, j, n));
return res;
}
// Driver program to test above
public static void main (String[] args)
{
int n = 3;
int mat[][] = { {4, 2, 1},
{3, 9, 6},
{11, 3, 15} };
System.out.println( "Largest zigzag sum: "
+ largestZigZag(mat, n));
}
}
// This code is contributed by anuj_67.
C#
1289
Chapter 173. Largest sum Zigzag sequence in a matrix
return zzs + mat[i,j];
}
// Returns largest possible
// sum of a Zizag sequence
// starting from top and ending
// at bottom.
static int largestZigZag(int [,]mat, int n)
{
// Consider all cells of
// top row as starting
// point
int res = 0;
for (int j = 0; j < n; j++)
res = Math.Max(res,
largestZigZagSumRec(mat, 0, j, n));
return res;
}
// Driver Code
public static void Main ()
{
int n = 3;
int [,]mat = {{4, 2, 1},
{3, 9, 6},
{11, 3, 15}};
Console.WriteLine("Largest zigzag sum: "
+ largestZigZag(mat, n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find the
// largest sum zigzag sequence
$MAX = 100;
// Returns largest sum of a
// Zigzag sequence starting
// from (i, j) and ending at
// a bottom cell.
1290
Chapter 173. Largest sum Zigzag sequence in a matrix
Output:
1291
Chapter 173. Largest sum Zigzag sequence in a matrix
Overlapping Subproblems
Considering the above implementation, for a matrix mat[][] of size 3 x 3, to find zigzag
sum(zzs) for an element mat(i,j), the following recursion tree is formed.
We can see that there are many subproblems which are solved again and again. So this
problem has Overlapping Substructure property and recomputation of same subproblems
can be avoided by either using Memoization or Tabulation. Following is a tabluated imple-
mentation for the LIS problem.
1292
Chapter 173. Largest sum Zigzag sequence in a matrix
int j, int n)
{
if (dp[i][j] != -1)
return dp[i][j];
// If we have reached bottom
if (i == n-1)
return (dp[i][j] = mat[i][j]);
// Find the largest sum by considering all
// possible next elements in sequence.
int zzs = 0;
for (int k=0; k<n; k++)
if (k != j)
zzs = max(zzs, largestZigZagSumRec(mat, i+1, k, n));
return (dp[i][j] = (zzs + mat[i][j]));
}
// Returns largest possible sum of a Zizag sequence
// starting from top and ending at bottom.
int largestZigZag(int mat[][MAX], int n)
{
memset(dp, -1, sizeof(dp));
// Consider all cells of top row as starting point
int res = 0;
for (int j=0; j<n; j++)
res = max(res, largestZigZagSumRec(mat, 0, j, n));
return res;
}
// Driver program to test above
int main()
{
int n = 3;
int mat[][MAX] = { {4, 2, 1},
{3, 9, 6},
{11, 3, 15}};
cout << "Largest zigzag sum: " << largestZigZag(mat, n);
return 0;
}
Output:
28
1293
Chapter 173. Largest sum Zigzag sequence in a matrix
Source
https://www.geeksforgeeks.org/largest-sum-zig-zag-sequence-in-a-matrix/
1294
Chapter 174
Asked in : Facebook
This problem is an extension of Largest Sum Subarray Problem.
1) We first compute maximum sum till every index and store it in an array maxSum[].
2) After filling the array, we use the sliding window concept of size k. Keep track of sum
of current k elements. To compute sum of current window, remove first element of previous
window and add current element. After getting the sum of current window, we add the
maxSum of the previous window, if it is greater than current max, then update it else not.
C++
1295
Chapter 174. Largest sum subarray with at-least k numbers
#include<bits/stdc++.h>
using namespace std;
// Returns maximum sum of a subarray with at-least
// k elements.
int maxSumWithK(int a[], int n, int k)
{
// maxSum[i] is going to store maximum sum
// till index i such that a[i] is part of the
// sum.
int maxSum[n];
maxSum[0] = a[0];
// We use Kadane's algorithm to fill maxSum[]
// Below code is taken from method 3 of
// https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/
int curr_max = a[0];
for (int i = 1; i < n; i++)
{
curr_max = max(a[i], curr_max+a[i]);
maxSum[i] = curr_max;
}
// Sum of first k elements
int sum = 0;
for (int i = 0; i < k; i++)
sum += a[i];
// Use the concept of sliding window
int result = sum;
for (int i = k; i < n; i++)
{
// Compute sum of k elements ending
// with a[i].
sum = sum + a[i] - a[i-k];
// Update result if required
result = max(result, sum);
// Include maximum sum till [i-k] also
// if it increases overall max.
result = max(result, sum + maxSum[i-k]);
}
return result;
}
// Driver code
int main()
1296
Chapter 174. Largest sum subarray with at-least k numbers
{
int a[] = {1, 2, 3, -10, -3};
int k = 4;
int n = sizeof(a)/sizeof(a[0]);
cout << maxSumWithK(a, n, k);
return 0;
}
Java
1297
Chapter 174. Largest sum subarray with at-least k numbers
Python3
1298
Chapter 174. Largest sum subarray with at-least k numbers
result = sum
for i in range(k, n):
# Compute sum of k elements
# ending with a[i].
sum = sum + a[i] - a[i-k]
# Update result if required
result = max(result, sum)
# Include maximum sum till [i-k] also
# if it increases overall max.
result = max(result, sum + maxSum[i-k])
return result
# Driver code
a = [1, 2, 3, -10, -3]
k = 4
n = len(a)
print(maxSumWithK(a, n, k))
# This code is contributed by Anant Agarwal.
PHP
<?php
// PHP program to find largest subarray
// sum with at-least k elements in it.
// Returns maximum sum of a subarray
// with at-least k elements.
function maxSumWithK($a, $n, $k)
{
// maxSum[i] is going to
// store maximum sum till
// index i such that a[i]
// is part of the sum.
$maxSum[0] = $a[0];
// We use Kadane's algorithm
// to fill maxSum[]
$curr_max = $a[0];
for ($i = 1; $i < $n; $i++)
{
$curr_max = max($a[$i], $curr_max+$a[$i]);
$maxSum[$i] = $curr_max;
1299
Chapter 174. Largest sum subarray with at-least k numbers
}
// Sum of first k elements
$sum = 0;
for ($i = 0; $i < $k; $i++)
$sum += $a[$i];
// Use the concept of
// sliding window
$result = $sum;
for ($i = $k; $i < $n; $i++)
{
// Compute sum of k
// elements ending
// with a[i].
$sum = $sum + $a[$i] - $a[$i - $k];
// Update result if required
$result = max($result, $sum);
// Include maximum sum till [i-k] also
// if it increases overall max.
$result = max($result, $sum +
$maxSum[$i - $k]);
}
return $result;
}
// Driver code
$a= array (1, 2, 3, -10, -3);
$k = 4;
$n = sizeof($a);
echo maxSumWithK($a, $n, $k);
// This code is contributed by m_kit
?>
Output:
-4
1300
Chapter 174. Largest sum subarray with at-least k numbers
Source
https://www.geeksforgeeks.org/largest-sum-subarray-least-k-numbers/
1301
Chapter 175
Examples :
Input : S = "()())"
Output : 4
Input : s = "()(((((()"
Output : 4
A brute force approach is to find all subsequence of the given string S and check for all
possible subsequence if it form a balanced sequence, if yes, compare it with maximum value.
The better approach is to use Dynamic Programming.
Longest Balananced Subsequence (LBS), can be recursively defined as below.
1302
Chapter 175. Length of Longest Balanced Subsequence
If str[i] == str[j]
LBS(str, i, j) = LBS(str, i + 1, j - 1) + 2
Else
LBS(str, i, j) = max(LBS(str, i, k) +
LBS(str, k + 1, j))
Where i <= k < j
Declare a 2D matrix dp[][], where our state dp[i][j] will denote the length of longest balanced
subsequence from index i to j. We will compute this state in order of increasing j - i. For a
particular state dp[i][j], we will try to match the jth symbol with kth symbol, that can be
done only if S[k] is ’(’ and S[j] is ’)’, we will take the max of 2 + dp[i][k - 1] + dp[k + 1][j -
1] for all such possible k and also max(dp[i + 1][j], dp[i][j - 1]) and put the value in dp[i][j].
In this way we can fill all the dp states. dp[0][length of string - 1] (considering 0 indexing)
will be our answer.
Below is the implementation of this approach:
C++
1303
Chapter 175. Length of Longest Balanced Subsequence
}
return dp[0][n - 1];
}
// Driver Code
int main()
{
char s[] = "()(((((()";
int n = strlen(s);
cout << maxLength(s, n) << endl;
return 0;
}
Java
1304
Chapter 175. Length of Longest Balanced Subsequence
}
return dp[0][n - 1];
}
// Driver Code
public static void main(String[] args)
{
String s = "()(((((()";
int n = s.length() ;
System.out.println(maxLength(s, n));
}
}
// This code is contributed by Prerna Saini
C#
1305
Chapter 175. Length of Longest Balanced Subsequence
return dp[0, n - 1];
}
// Driver Code
public static void Main()
{
string s = "()(((((()";
int n = s.Length ;
Console.WriteLine(maxLength(s, n));
}
}
// This code is contributed by vt_m.
Output:
Source
https://www.geeksforgeeks.org/length-longest-balanced-subsequence/
1306
Chapter 176
Input : X = "aieef"
Y = "klaief"
Output : aie
Input : X = "geeksforgeeks"
Y = "feroeeks"
Output : eoee
Source
https://www.geeksforgeeks.org/length-of-longest-common-subsequence-containing-vowels/
1307
Chapter 176. Length of longest common subsequence containing vowels
C++
1308
Chapter 176. Length of longest common subsequence containing vowels
Java
// Java implementation to find the
// length of longest common subsequence
// which contains all vowel characters
class GFG
{
// function to check whether ‘ch’
// is a vowel or not
static boolean isVowel(char ch)
{
if (ch == ‘a’ || ch == ‘e’ ||
ch == ‘i’ || ch == ‘o’ ||
ch == ‘u’)
return true;
return false;
}
// function to find the length of
// longest common subsequence which
// contains all vowel characters
static int lcs(String X, String Y,
int m, int n)
{
int L[][] = new int[m + 1][n + 1];
int i, j;
// Following steps build L[m+1][n+1]
// in bottom up fashion. Note that
// L[i][j] contains length of LCS of
// X[0..i-1] and Y[0..j-1]
for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if
((X.charAt(i - 1) == Y.charAt(j - 1)) && isVowel(X.charAt(i - 1))) L[i][j] = L[i - 1][j - 1] +
1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for
X[0..n-1] and Y[0..m-1] // which contains all vowel characters return L[m][n]; } // Driver
Code public static void main(String[] args) { String X = ”aieef”; String Y = ”klaief”; int
1309
Chapter 176. Length of longest common subsequence containing vowels
Length of LCS = 3
1310
Chapter 177
Input : ((()
Output : 2
Explanation : ()
Input: )()())
Output : 4
Explanation: ()()
Input: ()(()))))
Output: 6
Explanation: ()(())
A Simple Approach is to find all the substrings of given string. For every string, check
if it is a valid string or not. If valid and length is more than maximum length so far, then
update maximum length. We can check whether a substring is valid or not in linear time
using a stack (See this for details). Time complexity of this solution is O(n2 .
An Efficient Solution can solve this problem in O(n) time. The idea is to store indexes
of previous starting brackets in a stack. The first element of stack is a special element that
provides index before beginning of valid substring (base for next valid string).
1311
Chapter 177. Length of the longest valid substring
2) Initialize result as 0.
3) Return result.
C++
1312
Chapter 177. Length of the longest valid substring
Java
1313
Chapter 177. Length of the longest valid substring
stk.push(-1);
// Initialize result
int result = 0;
// Traverse all characters of given string
for (int i=0; i<n; i++)
{
// If opening bracket, push index of it
if (str.charAt(i) == '(')
stk.push(i);
else // If closing bracket, i.e.,str[i] = ')'
{
// Pop the previous opening bracket's index
stk.pop();
// Check if this length formed with base of
// current valid substring is more than max
// so far
if (!stk.empty())
result = Math.max(result, i - stk.peek());
// If stack is empty. push current index as
// base for next valid substring (if any)
else stk.push(i);
}
}
return result;
}
// Driver method
public static void main(String[] args)
{
String str = "((()()";
System.out.println(findMaxLen(str));
str = "()(()))))";
System.out.println(findMaxLen(str));
}
}
Python
1314
Chapter 177. Length of the longest valid substring
def findMaxLen(string):
n = len(string)
# Create a stack and push -1 as initial index to it.
stk = []
stk.append(-1)
# Initialize result
result = 0
# Traverse all characters of given string
for i in xrange(n):
# If opening bracket, push index of it
if string[i] == '(':
stk.append(i)
else: # If closing bracket, i.e., str[i] = ')'
# Pop the previous opening bracket's index
stk.pop()
# Check if this length formed with base of
# current valid substring is more than max
# so far
if len(stk) != 0:
result = max(result, i - stk[len(stk)-1])
# If stack is empty. push current index as
# base for next valid substring (if any)
else:
stk.append(i)
return result
# Driver program
string = "((()()"
print findMaxLen(string)
string = "()(()))))"
print findMaxLen(string)
# This code is contributed by Bhavya Jain
Output:
1315
Chapter 177. Length of the longest valid substring
Thanks to Gaurav Ahirwar and Ekta Goel. for suggesting above approach.
Source
https://www.geeksforgeeks.org/length-of-the-longest-valid-substring/
1316
Chapter 178
1317
Chapter 178. Level Ancestor Problem
Below is the algorithm to fill the ancestor matrix and depth of each node using dynamic
programming. Here, we denote root node as R and initially assume the ancestor of root
node as 0. We also initialize depth array with -1 means the depth of the current node is
not set and we need to find its depth. If the depth of the current node is not equal to -1
means we have already computed its depth.
In the given figure we need to compute 1st level ancestor of the node with value 8. First,
we make ancestor matrix which stores 2ith ancestor of nodes. Now, 20 ancestor of node 8
is 10 and similarly 20 ancestor of node 10 is 9 and for node 9 it is 1 and for node 1 it is 5.
Based on the above algorithm 1st level ancestor of node 8 is( depth(8)-1 )th ancestor of
node 8. We have pre computed depth of each node and depth of 8 is 5 so we finally need to
1318
Chapter 178. Level Ancestor Problem
find (5-1) = 4th ancestor of node 8 which is equal to 21 th ancestor of [21 ancestor of
node 8] and 21 th ancestor of node 8 is 20 th ancestor of [20 th ancestor of node 8].
So, 20 th ancestor of [20 th ancestor of node 8] is node with value 9 and 21 th ancestor
of node 9 is node with value 5. Thus in this way we can compute all query in O(logn) time
complexity.
1319
Chapter 178. Level Ancestor Problem
// if ancestor of current node is 0 means it
// does not have root node at its 2th power
// on its path so its depth is 2^(index of
// last non zero ancestor means j-1) + depth
// of 2^(j-1) th ancestor
else if (ancstr[node[i]][j] == 0 &&
node[i] != R && depth[node[i]] == -1) {
depth[node[i]] = pow(2, j - 1) +
depth[ancstr[node[i]][j - 1]];
}
}
}
}
// c -> it represent child
// p -> it represent ancestor
// i -> it represent node number
// p=0 means the node is root node
// R represent root node
// here also we pass reference of 2D matrix and depth
// vector so that the change made occur directly to
// the original matrix and original vector
void constructGraph(vector<vector<int> >& ancstr,
int* node, vector<int>& depth, int* isNode,
int c, int p, int i)
{
// enter the node in node array
// it stores all the nodes in the graph
node[i] = c;
// to confirm that no child node have 2 ancestors
if (isNode == 0) {
isNode = 1;
// make ancestor of x as y
ancstr[0] = p;
// ifits first ancestor is root than its depth is 1
if (R == p) {
depth = 1;
}
}
return;
}
// this function will delete leaf node
// x is node to be deleted
1320
Chapter 178. Level Ancestor Problem
1321
Chapter 178. Level Ancestor Problem
j++;
}
return;
}
// LA function to find Lth level ancestor of node x
void LA(vector<vector<int> >& ancstr, vector<int> depth,
int* isNode, int x, int L)
{
int j = 0;
int temp = x;
// to check if node is present in graph or not
if (isNode[x] == 0) {
cout << "Node is not present in graph " << endl;
return;
}
// we change L as depth of node x -
int k = depth[x] - L;
// int q = k;
// in this loop we decrease the value of k by k/2 and
// increment j by 1 after each iteration, and check for set bit
// if we get set bit then we update x with jth ancestor of x
// as k becomes less than or equal to zero means we
// reach to kth level ancestor
while (k > 0) {
// to check if last bit is 1 or not
if (k & 1) {
x = ancstr[x][j];
}
// use of shift operator to make k = k/2
// after every iteration
k = k >> 1;
j++;
}
cout << L << "th level acestor of node "
<< temp << " is = " << x << endl;
return;
}
int main()
{
// n represent number of nodes
int n = 12;
1322
Chapter 178. Level Ancestor Problem
// initialization of ancestor matrix
// suppose max range of node is up to 1000
// if there are 1000 nodes than also length
// of ancestor matrix will not exceed 10
vector<vector<int> > ancestor(1000, vector<int>(10));
// this vector is used to store depth of each node.
vector<int> depth(1000);
// fill function is used to initialize depth with -1
fill(depth.begin(), depth.end(), -1);
// node array is used to store all nodes
int* node = new int[1000];
// isNode is an array to check whether a
// node is present in graph or not
int* isNode = new int[1000];
// memset function to initialize isNode array with 0
memset(isNode, 0, 1000 * sizeof(int));
// function to calculate len
// len -> it is the maximum length of array to
// hold ancestor of each node.
int len = getLen(n);
// R stores root node
R = 2;
// construction of graph
// here 0 represent that the node is root node
constructGraph(ancestor, node, depth, isNode, 2, 0, 0);
constructGraph(ancestor, node, depth, isNode, 5, 2, 1);
constructGraph(ancestor, node, depth, isNode, 3, 5, 2);
constructGraph(ancestor, node, depth, isNode, 4, 5, 3);
constructGraph(ancestor, node, depth, isNode, 1, 5, 4);
constructGraph(ancestor, node, depth, isNode, 7, 1, 5);
constructGraph(ancestor, node, depth, isNode, 9, 1, 6);
constructGraph(ancestor, node, depth, isNode, 10, 9, 7);
constructGraph(ancestor, node, depth, isNode, 11, 10, 8);
constructGraph(ancestor, node, depth, isNode, 6, 10, 9);
constructGraph(ancestor, node, depth, isNode, 8, 10, 10);
// function to pre compute ancestor matrix
setancestor(ancestor, depth, node, len, n);
1323
Chapter 178. Level Ancestor Problem
Output:
Source
https://www.geeksforgeeks.org/level-ancestor-problem/
1324
Chapter 179
Lobb Number
Lobb Number is also used to count the number of ways in which n + m copies of the value
+1 and n – m copies of the value -1 may be arranged into a sequence such that all of the
partial sums of the sequence are non- negative.
Examples :
Input : n = 3, m = 2
Output : 5
Input : n =5, m =3
Output :35
The idea is simple, we use a function that computes binomial coefficients for given values.
Using this function and above formula, we can compute Lobb numbers.
C++
1325
Chapter 179. Lobb Number
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k)
{
int C[n + 1][k + 1];
// Calculate value of Binomial Coefficient in
// bottom up manner
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= min(i, k); j++) {
// Base Cases
if (j == 0 || j == i)
C[i][j] = 1;
// Calculate value using previously stored values
else
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
return C[n][k];
}
// Return the Lm, n Lobb Number.
int lobb(int n, int m)
{
return ((2 * m + 1) * binomialCoeff(2 * n, m + n)) / (m + n + 1);
}
// Driven Program
int main()
{
int n = 5, m = 3;
cout << lobb(n, m) << endl;
return 0;
}
Java
1326
Chapter 179. Lobb Number
Python 3
1327
Chapter 179. Lobb Number
C = [[0 for j in range(k + 1)]
for i in range(n + 1)]
# Calculate value of Binomial
# Coefficient in bottom up manner
for i in range(0, n + 1):
for j in range(0, min(i, k) + 1):
# Base Cases
if (j == 0 or j == i):
C[i][j] = 1
# Calculate value using
# previously stored values
else:
C[i][j] = (C[i - 1][j - 1]
+ C[i - 1][j])
return C[n][k]
# Return the Lm, n Lobb Number.
def lobb(n, m):
return (((2 * m + 1) *
binomialCoeff(2 * n, m + n))
/ (m + n + 1))
# Driven Program
n = 5
m = 3
print(int(lobb(n, m)))
# This code is contributed by
# Smitha Dinesh Semwal
C#
1328
Chapter 179. Lobb Number
PHP
<?php
// PHP Program to find Ln,
// m Lobb Number.
$MAXN =109;
1329
Chapter 179. Lobb Number
// Returns value of Binomial
// Coefficient C(n, k)
function binomialCoeff($n, $k)
{
$C= array(array());
// Calculate value of Binomial
// Coefficient in bottom up manner
for ($i = 0; $i <= $n; $i++)
{
for ($j = 0; $j <= min($i, $k); $j++)
{
// Base Cases
if ($j == 0 || $j == $i)
$C[$i][$j] = 1;
// Calculate value using p
// reviously stored values
else
$C[$i][$j] = $C[$i - 1][$j - 1] +
$C[$i - 1][$j];
}
}
return $C[$n][$k];
}
// Return the Lm, n Lobb Number.
function lobb($n, int $m)
{
return ((2 * $m + 1) *
binomialCoeff(2 * $n, $m + $n)) /
($m + $n + 1);
}
// Driven Code
$n = 5;$m = 3;
echo lobb($n, $m);
// This code is contributed by anuj_67.
?>
Output :
35
1330
Chapter 179. Lobb Number
Source
https://www.geeksforgeeks.org/lobb-number/
1331
Chapter 180
1332
Chapter 180. Longest Common Substring (Space optimized DP solution)
We have discussed Dynamic programming based solution for Longest common substring.
The auxiliary space used by the solution is O(m*n), where m and n are lengths of string X
and Y. The space used by solution can be reduced to O(2*n).
Suppose we are at position mat[i][j]. Now if X[i-1] == Y[j-1], then we add the value of
mat[i-1][j-1] to our result. That is we add value from previous row and value for all other
rows below the previous row are never used. So, at a time we are using only two consecutive
rows. This observation can be used to reduce the space required to find length of longest
common substring.
Instead of creating a matrix of size m*n, we create a matrix of size 2*n. A variable currRow
is used to represent that either row 0 or row 1 of this matrix is currently used to find
length. Initially row 0 is used as current row for the case when length of string X is zero.
At the end of each iteration, current row is made previous row and previous row is made
new current row.
C++
1333
Chapter 180. Longest Common Substring (Space optimized DP solution)
Java
1334
Chapter 180. Longest Common Substring (Space optimized DP solution)
1335
Chapter 180. Longest Common Substring (Space optimized DP solution)
{
len[currRow][j] = 0;
}
}
// Make current row as previous
// row and previous row as
// new current row.
currRow = 1 - currRow;
}
return result;
}
// Driver Code
public static void main(String args[])
{
String X = "GeeksforGeeks";
String Y = "GeeksQuiz";
System.out.print(LCSubStr(X, Y));
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
C#
1336
Chapter 180. Longest Common Substring (Space optimized DP solution)
1337
Chapter 180. Longest Common Substring (Space optimized DP solution)
// This code is contributed by
// Manish Shaw (manishshaw1)
PHP
<?php
// Space optimized PHP implementation
// of longest common substring.
// Function to find
// longest common substring.
function LCSubStr($X, $Y)
{
// Find length of
// both the strings.
$m = strlen($X);
$n = strlen($Y);
// Variable to store length
// of longest common substring.
$result = 0;
// Matrix to store result of two
// consecutive rows at a time.
$len = array(array(), array(), );
// Variable to represent which
// row of matrix is current row.
$currRow = 0;
// For a particular value of
// i and j, len[currRow][j]
// stores length of longest
// common substring in string
// X[0..i] and Y[0..j].
for ($i = 0; $i <= $m; $i++)
{
for ($j = 0; $j <= $n; $j++)
{
if ($i == 0 || $j == 0)
{
$len[$currRow][$j] = 0;
}
else if ($X[$i - 1] == $Y[$j - 1])
{
$len[$currRow][$j] =
$len[1 - $currRow][$j - 1] + 1;
1338
Chapter 180. Longest Common Substring (Space optimized DP solution)
$result = max($result,
$len[$currRow][$j]);
}
else
{
$len[$currRow][$j] = 0;
}
}
// Make current row as
// previous row and previous
// row as new current row.
$currRow = 1 - $currRow;
}
return $result;
}
// Driver Code
$X = "GeeksforGeeks";
$Y = "GeeksQuiz";
print (LCSubStr($X, $Y));
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output :
Source
https://www.geeksforgeeks.org/longest-common-substring-space-optimized-dp-solution/
1339
Chapter 181
C++
1340
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
1341
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
int n = sizeof(arr1)/sizeof(arr1[0]);
int m = sizeof(arr2)/sizeof(arr2[0]);
cout << "Length of LCIS is "
<< LCIS(arr1, n, arr2, m);
return (0);
}
Java
1342
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
element of arr1 */
if (arr1[i] > arr2[j])
if (table[j] > current)
current = table[j];
}
}
// The maximum value in table[] is out
// result
int result = 0;
for (int i=0; i<m; i++)
if (table[i] > result)
result = table[i];
return result;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr1[] = {3, 4, 9, 1};
int arr2[] = {5, 3, 8, 9, 10, 2, 1};
int n = arr1.length;
int m = arr2.length;
System.out.println("Length of LCIS is " +
LCIS(arr1, n, arr2, m));
}
}
// This code is contributed by Prerna Saini
C#
1343
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
1344
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
Console.Write("Length of LCIS is " +
LCIS(arr1, n, arr2, m));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP Program to find length of
// the Longest Common Increasing
// Subsequence (LCIS)
// Returns the length and the LCIS
// of two arrays arr1[0..n-1] and
// arr2[0..m-1]
function LCIS($arr1, $n, $arr2, $m)
{
// table[j] is going to store
// length of LCIS ending with
// arr2[j]. We initialize it as 0,
$table = Array();
//int table[m];
for ($j = 0; $j < $m; $j++)
$table[$j] = 0;
// Traverse all elements of arr1[]
for ($i = 0; $i < $n; $i++)
{
// Initialize current
// length of LCIS
$current = 0;
// For each element of
// arr1[], trvarse all
// elements of arr2[].
for ($j = 0; $j < $m; $j++)
{
// If both the array have
// same elements. Note that
// we don't break the loop here.
if ($arr1[$i] == $arr2[$j])
if ($current + 1 > $table[$j])
$table[$j] = $current + 1;
1345
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
/* Now seek for previous smaller
common element for current
element of arr1 */
if ($arr1[$i] > $arr2[$j])
if ($table[$j] > $current)
$current = $table[$j];
}
}
// The maximum value in
// table[] is out result
$result = 0;
for ($i = 0; $i < $m; $i++)
if ($table[$i] > $result)
$result = $table[$i];
return $result;
}
// Driver Code
$arr1 = array (3, 4, 9, 1);
$arr2 = array (5, 3, 8, 9, 10, 2, 1);
$n = sizeof($arr1);
$m = sizeof($arr2);
echo "Length of LCIS is ",
LCIS($arr1, $n, $arr2, $m);
// This code is contributed by ajit
?>
Output :
Length of LCIS is 2
C++
1346
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
1347
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
Java
1348
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
1349
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
// The maximum value in table[] is out
// result
int result = 0, index = -1;
for (int i = 0; i < m; i++)
{
if (table[i] > result)
{
result = table[i];
index = i;
}
}
// LCIS is going to store elements
// of LCIS
int lcis[] = new int[result];
for (int i = 0; index != -1; i++)
{
lcis[i] = arr2[index];
index = parent[index];
}
System.out.print("The LCIS is : ");
for (int i = result - 1; i >= 0; i--)
System.out.print(lcis[i] + " ");
return result;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr1[] = {3, 4, 9, 1};
int arr2[] = {5, 3, 8, 9, 10, 2, 1};
int n = arr1.length;
int m = arr2.length;
System.out.println("\nLength of LCIS is "+
LCIS(arr1, n, arr2, m));
}
}
// This code is contributed by Prerna Saini
C#
1350
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
1351
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
{
if (table[j] > current)
{
current = table[j];
last = j;
}
}
}
}
// The maximum value in
// table[] is out result
int result = 0, index = -1;
for (int i = 0; i < m; i++)
{
if (table[i] > result)
{
result = table[i];
index = i;
}
}
// LCIS is going to store
// elements of LCIS
int []lcis = new int[result];
for (int i = 0; index != -1; i++)
{
lcis[i] = arr2[index];
index = parent[index];
}
Console.Write("The LCIS is : ");
for (int i = result - 1; i >= 0; i--)
Console.Write(lcis[i] + " ");
return result;
}
// Driver Code
static public void Main ()
{
int []arr1 = {3, 4, 9, 1};
int []arr2 = {5, 3, 8, 9,
10, 2, 1};
int n = arr1.Length;
int m = arr2.Length;
1352
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
PHP
<?php
// A PHP Program to find
// length of the Longest
// Common Increasing
// Subsequence (LCIS)
// Returns the length and
// the LCIS of two arrays
// arr1[0..n-1] and
// arr2[0..m-1] and prints LCIS
function LCIS($arr1, $n,
$arr2, $m)
{
// table[j] is going to
// store length of LCIS
// ending with arr2[j].
// We initialize it as 0,
$table = Array(); $parent = Array();
for ($j = 0; $j < $m; $j++)
$table[$j] = 0;
// Traverse all
// elements of arr1[]
for ($i = 0 ; $i < $n; $i++)
{
// Initialize current
// length of LCIS
$current = 0; $last = -1;
// For each element of
// arr1[], trvarse all
// elements of arr2[].
for ($j = 0; $j < $m; $j++)
{
// If both the array have
// same elements. Note that
1353
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
1354
Chapter 181. Longest Common Increasing Subsequence (LCS + LIS)
Output :
The LCIS is : 3 9
Length of LCIS is 2
Source
https://www.geeksforgeeks.org/longest-common-increasing-subsequence-lcs-lis/
1355
Chapter 182
Input : P = { 8, 3 }
Q = { 1, 3 }
K = 1
Output : 2
If we change first element of first
sequence from 8 to 1, both sequences
become same.
Input : P = { 1, 2, 3, 4, 5 }
Q = { 5, 3, 1, 4, 2 }
K = 1
Output : 3
By changing first element of first
sequence to 5 to get the LCS ( 5, 3, 4 }.
The idea is to use Dynamic Programming. Define a 3D matrix dp[][][], where dp[i][j][k]
defines the Longest Common Subsequence for the first i numbers of first array, first j number
of second array when we are allowed to change at max k number in the first array.
Therefore, recursion will look like
1356
Chapter 182. Longest Common Subsequence with at most k changes allowed
If P[i] != Q[j],
dp[i][j][k] = max(dp[i - 1][j][k],
dp[i][j - 1][k],
dp[i - 1][j - 1][k - 1] + 1)
If P[i] == Q[j],
dp[i][j][k] = max(dp[i - 1][j][k],
dp[i][j - 1][k],
dp[i - 1][j - 1][k] + 1)
1357
Chapter 182. Longest Common Subsequence with at most k changes allowed
arr2, m - 1, k - 1));
return ans;
}
// Driven Program
int main()
{
int k = 1;
int arr1[] = { 1, 2, 3, 4, 5 };
int arr2[] = { 5, 3, 1, 4, 2 };
int n = sizeof(arr1) / sizeof(arr1[0]);
int m = sizeof(arr2) / sizeof(arr2[0]);
int dp[MAX][MAX][MAX];
memset(dp, -1, sizeof(dp));
cout << lcs(dp, arr1, n, arr2, m, k) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/longest-common-subsequence-with-at-most-k-changes-allowed/
1358
Chapter 183
The naive solution for this problem is to generate all subsequences of both given sequences
and find the longest matching subsequence. This solution is exponential in term of time com-
plexity. The general recursive solution of the problem is to generate all subsequences of both
given sequences and find the longest matching subsequence. Total possible combinations
will be 2n . Hence recursive solution will take O(2n ).
Optimal Substructure:
• Let the input sequences be X[0..m-1] and Y[0..n-1] of lengths m and n respectively.
And let L(X[0..m-1], Y[0..n-1]) be the length of LCS of the two sequences X and Y.
Following is the recursive definition of L(X[0..m-1], Y[0..n-1]).
• If last characters of both sequences match (or X[m-1] == Y[n-1]) then L(X[0..m-1],
Y[0..n-1]) = 1 + L(X[0..m-2], Y[0..n-2])
• If last characters of both sequences do not match (or X[m-1] != Y[n-1]) then L(X[0..m-
1], Y[0..n-1]) = MAX ( L(X[0..m-2], Y[0..n-1]), L(X[0..m-1], Y[0..n-2])
1359
Chapter 183. Longest Common Subsequence | DP using Memoization
Output:
Length of LCS: 4
lcs("AXYT", "AYZX")
1360
Chapter 183. Longest Common Subsequence | DP using Memoization
/ \
lcs("AXY", "AYZX") lcs("AXYT", "AYZ")
/ \ / \
lcs("AX", "AYZX") lcs("AXY", "AYZ") lcs("AXY", "AYZ") lcs("AXYT", "AY")
In the above partial recursion tree, lcs(“AXY”, “AYZ”) is being solved twice. On
drawing the complete recursion tree, it has been observed that there are many subproblems
which are solved again and again. So this problem has Overlapping Substructure prop-
erty and recomputation of same subproblems can be avoided by either using Memoization
or Tabulation. The tabulation method has been discussed here.
A common point of observation to use memoization in the recursive code will be the two
non-constant arguments M and N in every function call. The function has 4 arguments,
but 2 arguments are constant which do not affect the Memoization. The repetitive calls occur
for N and M which have been called previously. Following the below steps will help us to
write the DP solution using memoization.
• Use a 2-D array to store the computed lcs(m, n) value at arr[m-1][n-1] as the
string index starts from 0.
• Whenever the function with the same argument m and n are called again, do not per-
form any further recursive call and return arr[m-1][n-1] as the previous computation
of the lcs(m, n) has already been stored in arr[m-1][n-1], hence reducing the recursive
calls that happen more then once.
1361
Chapter 183. Longest Common Subsequence | DP using Memoization
Output:
Length of LCS: 4
Time Complexity: O(N * M), where N and M is length of the first and second string
respectively.
Auxiliary Space: (N * M)
1362
Chapter 183. Longest Common Subsequence | DP using Memoization
Source
https://www.geeksforgeeks.org/longest-common-subsequence-dp-using-memoization/
1363
Chapter 184
Longest Decreasing
Subsequence
Input: arr[] = [15, 27, 14, 38, 63, 55, 46, 65, 85]
Output: 3
Explanation: The longest decreasing sub sequence is {63, 55, 46}
Input: arr[] = {50, 3, 10, 7, 40, 80}
Output: 3
Explanation: The longest decreasing subsequence is {50, 10, 7}
lds[i] = 1 + max( lds[j] ) where i > j > 0 and arr[j] > arr[i] or
lds[i] = 1, if no such j exists.
To find the LDS for a given array, we need to return max(lds[i]) where n > i > 0.
C++
1364
Chapter 184. Longest Decreasing Subsequence
Java
1365
Chapter 184. Longest Decreasing Subsequence
import java.io.*;
class GFG
{
// Function that returns the
// length of the longest
// decreasing subsequence
static int lds(int arr[], int n)
{
int lds[] = new int[n];
int i, j, max = 0;
// Initialize LDS with 1
// for all index. The minimum
// LDS starting with any
// element is always 1
for (i = 0; i < n; i++)
lds[i] = 1;
// Compute LDS from every
// index in bottom up manner
for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (arr[i] < arr[j] &&
lds[i] < lds[j] + 1)
lds[i] = lds[j] + 1;
// Select the maximum
// of all the LDS values
for (i = 0; i < n; i++)
if (max < lds[i])
max = lds[i];
// returns the length
// of the LDS
return max;
}
// Driver Code
public static void main (String[] args)
{
int arr[] = { 15, 27, 14, 38,
63, 55, 46, 65, 85 };
int n = arr.length;
System.out.print("Length of LDS is " +
lds(arr, n));
}
}
1366
Chapter 184. Longest Decreasing Subsequence
// This code is contributed by anuj_67.
C#
1367
Chapter 184. Longest Decreasing Subsequence
{
int []arr = { 15, 27, 14, 38,
63, 55, 46, 65, 85 };
int n = arr.Length;
Console.Write("Length of LDS is " +
lds(arr, n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find the
// length of the longest
// decreasing subsequence
// Function that returns the
// length of the longest
// decreasing subsequence
function lds($arr, $n)
{
$lds = array();
$i; $j; $max = 0;
// Initialize LDS with 1
// for all index The minimum
// LDS starting with any
// element is always 1
for ($i = 0; $i < $n; $i++)
$lds[$i] = 1;
// Compute LDS from every
// index in bottom up manner
for ($i = 1; $i < $n; $i++)
for ($j = 0; $j < $i; $j++)
if ($arr[$i] < $arr[$j] and
$lds[$i] < $lds[$j] + 1)
{
$lds[$i] = $lds[$j] + 1;
}
// Select the maximum
// of all the LDS values
for ($i = 0; $i < $n; $i++)
if ($max < $lds[$i])
1368
Chapter 184. Longest Decreasing Subsequence
$max = $lds[$i];
// returns the length
// of the LDS
return $max;
}
// Driver Code
$arr = array(15, 27, 14, 38, 63,
55, 46, 65, 85);
$n = count($arr);
echo "Length of LDS is " ,
lds($arr, $n);
// This code is contributed by anuj_67.
?>
Output :
Length of LDS is 3
Source
https://www.geeksforgeeks.org/longest-decreasing-subsequence/
1369
Chapter 185
Longest Even Length Substring such that Sum of First and Second Half is same - Geeks-
forGeeks
Given a string ‘str’ of digits, find length of the longest substring of ‘str’, such that the length
of the substring is 2k digits and sum of left k digits is equal to the sum of right k digits.
Examples :
1370
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
#include<string.h>
int findLength(char *str)
{
int n = strlen(str);
int maxlen =0; // Initialize result
// Choose starting point of every substring
for (int i=0; i<n; i++)
{
// Choose ending point of even length substring
for (int j =i+1; j<n; j += 2)
{
int length = j-i+1;//Find length of current substr
// Calculate left & right sums for current substr
int leftsum = 0, rightsum =0;
for (int k =0; k<length/2; k++)
{
leftsum += (str[i+k]-'0');
rightsum += (str[i+k+length/2]-'0');
}
// Update result if needed
if (leftsum == rightsum && maxlen < length)
maxlen = length;
}
}
return maxlen;
}
// Driver program to test above function
int main(void)
{
char str[] = "1538023";
printf("Length of the substring is %d", findLength(str));
return 0;
}
Java
1371
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
Python3
1372
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
C#
1373
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
1374
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
}
// This code is contrtibuted by nitin mittal
Output:
1375
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
Java
1376
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
Output:
Time complexity of the above solution is O(n2 ), but it requires O(n2 ) extra space.
[A O(n2 ) and O(n) extra space solution]
The idea is to use a single dimensional array to store cumulative sum.
C++
1377
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
{
int sum[n+1]; // To store cumulative sum from first digit to nth digit
sum[0] = 0;
/* Store cumulative sum of digits from first to last digit */
for (int i = 1; i <= n; i++)
sum[i] = (sum[i-1] + str[i-1] - '0'); /* convert chars to int */
int ans = 0; // initialize result
/* consider all even length substrings one by one */
for (int len = 2; len <= n; len += 2)
{
for (int i = 0; i <= n-len; i++)
{
int j = i + len - 1;
/* Sum of first and second half is same than update ans */
if (sum[i+len/2] - sum[i] == sum[i+len] - sum[i+len/2])
ans = max(ans, len);
}
}
return ans;
}
// Driver program to test above function
int main()
{
string str = "123123";
cout << "Length of the substring is " << findLength(str, str.length());
return 0;
}
Java
1378
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
C#
1379
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
Output:
1380
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
1381
Chapter 185. Longest Even Length Substring such that Sum of First and Second Half is
same
Output:
Source
https://www.geeksforgeeks.org/longest-even-length-substring-sum-first-second-half/
1382
Chapter 186
This problem is similar to Longest Arithmetic Progression Problem. We can solve this
problem using Dynamic Programming.
We first sort the given set. We use an auxiliary table L[n][n] to store results of subproblems.
An entry L[i][j] in this table stores LLGP with set[i] and set[j] as first two elements of GP
and j > i. The table is filled from bottom right to top left. To fill the table, j (second
element in GP) is first fixed. i and k are searched for a fixed j. If i and k are found such
that i, j, k form an GP, then the value of L[i][j] is set as L[j][k] + 1. Note that the value of
L[j][k] must have been filled before as the loop traverses from right to left columns.
Following is C++ implementation of the Dynamic Programming algorithm.
1383
Chapter 186. Longest Geometric Progression
1384
Chapter 186. Longest Geometric Progression
// i, j and k form GP, LLGP with i and j as
// first two elements is equal to LLGP with
// j and k as first two elements plus 1.
// L[j][k] must have been filled before as
// we run the loop from right side
else
{
L[i][j] = L[j][k] + 1;
// Update overall LLGP
if (L[i][j] > llgp)
llgp = L[i][j];
// Change i and k to fill more L[i][j]
// values for current j
--i;
++k;
}
}
// If the loop was stopped due to k becoming
// more than n-1, set the remaining entties
// in column j as 1 or 2 based on divisibility
// of set[j] by set[i]
while (i >= 0)
{
if (set[j] % set[i] == 0)
L[i][j] = 2;
else
L[i][j] = 1;
--i;
}
}
// Return result
return llgp;
}
// Driver code
int main()
{
int set1[] = {1, 3, 9, 27, 81, 243};
int n1 = sizeof(set1)/sizeof(set1[0]);
cout << lenOfLongestGP(set1, n1) << "n";
1385
Chapter 186. Longest Geometric Progression
Output:
6
4
1
Source
https://www.geeksforgeeks.org/longest-geometric-progression/
1386
Chapter 187
Input : arr[] = {1, 12, 2, 22, 5, 30, 31, 14, 17, 11}
Output : 5
Naive Approach: Consider all subsequences and select the ones with alternate odd even
numbers in increasing order. Out of them select the longest one. This has an exponential
time complexity.
Efficient Approach:
Let L(i) be the length of the LIOES (Longest Increasing Odd Even Subsequence) ending at
index i such that arr[i] is the last element of the LIOES.
Then, L(i) can be recursively written as:
L(i) = 1 + max( L(j) ) where 0 < j < i and (arr[j] < arr[i]) and (arr[i]+arr[j])%2 != 0; or
L(i) = 1, if no such j exists.
To find the LIOES for a given array, we need to return max(L(i)) where 0 < i < n.
A dynamic programming approach has been implemented below for the above mentioned
recursive relation.
1387
Chapter 187. Longest Increasing Odd Even Subsequence
C++
1388
Chapter 187. Longest Increasing Odd Even Subsequence
Java
1389
Chapter 187. Longest Increasing Odd Even Subsequence
}
// driver function
public static void main(String argc[]){
int[] arr = new int[]{ 1, 12, 2, 22,
5, 30, 31, 14, 17, 11 };
int n = 10;
System.out.println("Longest Increasing Odd"
+ " Even Subsequence: "
+ longOddEvenIncSeq(arr, n));
}
}
/* This code is contributed by Sagar Shukla */
Python3
1390
Chapter 187. Longest Increasing Odd Even Subsequence
maxLen = lioes[i]
# required maximum length
return maxLen
# Driver to test above
arr = [ 1, 12, 2, 22, 5, 30, 31, 14, 17, 11 ]
n = len(arr)
print("Longest Increasing Odd Even " +
"Subsequence: ",longOddEvenIncSeq(arr, n))
# This code is contributed by "Sharad_Bhardwaj".
C#
1391
Chapter 187. Longest Increasing Odd Even Subsequence
Output:
Source
https://www.geeksforgeeks.org/longest-increasing-odd-even-subsequence/
1392
Chapter 188
Input : N = 4, M = 4
m[][] = { { 1, 2, 3, 4 },
{ 2, 2, 3, 4 },
{ 3, 2, 3, 4 },
{ 4, 5, 6, 7 } };
Output : 7
Longest path is 1 2 3 4 5 6 7.
Input : N = 2, M =2
m[][] = { { 1, 2 },
{ 3, 4 } };
Output :3
Longest path is either 1 2 4 or
1 3 4.
The idea is to use dynamic programming. Maintain the 2D matrix, dp[][], where dp[i][j]
store the value of length of longest increasing sequence for sub matrix starting from ith row
and j-th column.
Let the longest increasing sub sequence values for m[i+1][j] and m[i][j+1] be known already
as v1 and v2 respectively. Then the value for m[i][j] will be max(v1, v2) + 1.
We can start from m[n-1][m-1] as base case with length of longest increasing sub sequence
1393
Chapter 188. Longest Increasing Path in Matrix
be 1, moving upwards and leftwards updating the value of cells. Then the LIP value for cell
m[0][0] will be the answer.
Below is the implementation of this approach:
C++
1394
Chapter 188. Longest Increasing Path in Matrix
return LIP(dp, mat, n, m, 0, 0);
}
// Driven Program
int main()
{
int mat[][MAX] = {
{ 1, 2, 3, 4 },
{ 2, 2, 3, 4 },
{ 3, 2, 3, 4 },
{ 4, 5, 6, 7 },
};
int n = 4, m = 4;
cout << wrapper(mat, n, m) << endl;
return 0;
}
Java
1395
Chapter 188. Longest Increasing Path in Matrix
Output:
Source
https://www.geeksforgeeks.org/longest-increasing-path-matrix/
1396
Chapter 189
1397
Chapter 189. Longest Increasing Subsequence Size (N log N)
In case of our original array {2, 5, 3}, note that we face same situation when we are adding
3 to increasing sequence {2, 5}. I just created two increasing sequences to make explanation
simple. Instead of two sequences, 3 can replace 5 in the sequence {2, 5}.
I know it will be confusing, I will clear it shortly!
The question is, when will it be safe to add or replace an element in the existing sequence?
Let us consider another sample A = {2, 5, 3}. Say, the next element is 1. How can it extend
the current sequences {2,3} or {2, 5}. Obviously, it can’t extend either. Yet, there is a
potential that the new smallest element can be start of an LIS. To make it clear, consider
the array is {2, 5, 3, 1, 2, 3, 4, 5, 6}. Making 1 as new sequence will create new sequence
which is largest.
The observation is, when we encounter new smallest element in the array, it can be a potential
candidate to start new sequence.
From the observations, we need to maintain lists of increasing sequences.
In general, we have set of active lists of varying length. We are adding an element A[i] to
these lists. We scan the lists (for end elements) in decreasing order of their length. We will
verify the end elements of all the lists to find a list whose end element is smaller than A[i]
(floor value).
Our strategy determined by the following conditions,
Note that at any instance during our construction of active lists, the following condition is
maintained.
“end element of smaller list is smaller than end elements of larger lists”.
It will be clear with an example, let us take example from wiki {0, 8, 4, 12, 2, 10, 6, 14, 1,
9, 5, 13, 3, 11, 7, 15}.
1398
Chapter 189. Longest Increasing Subsequence Size (N log N)
1399
Chapter 189. Longest Increasing Subsequence Size (N log N)
0, 2, 6.
0, 2, 6, 9.
0, 2, 6, 14. Discarded.
-----------------------------------------------------------------------------
A[10] = 5. Case 3. Clone, extend and discard.
0.
0, 1.
0, 1, 5.
0, 2, 6. Discarded.
0, 2, 6, 9.
-----------------------------------------------------------------------------
A[11] = 13. Case 2. Clone and extend.
0.
0, 1.
0, 1, 5.
0, 2, 6, 9.
0, 2, 6, 9, 13.
-----------------------------------------------------------------------------
A[12] = 3. Case 3. Clone, extend and discard.
0.
0, 1.
0, 1, 3.
0, 1, 5. Discarded.
0, 2, 6, 9.
0, 2, 6, 9, 13.
-----------------------------------------------------------------------------
A[13] = 11. Case 3. Clone, extend and discard.
0.
0, 1.
0, 1, 3.
0, 2, 6, 9.
0, 2, 6, 9, 11.
0, 2, 6, 9, 13. Discarded.
-----------------------------------------------------------------------------
A[14] = 7. Case 3. Clone, extend and discard.
0.
0, 1.
0, 1, 3.
0, 1, 3, 7.
0, 2, 6, 9. Discarded.
0, 2, 6, 9, 11.
----------------------------------------------------------------------------
A[15] = 15. Case 2. Clone and extend.
0.
0, 1.
0, 1, 3.
0, 1, 3, 7.
0, 2, 6, 9, 11.
1400
Chapter 189. Longest Increasing Subsequence Size (N log N)
1401
Chapter 189. Longest Increasing Subsequence Size (N log N)
Given below is code to find length of LIS (updated to C++11 code, no C-style arrays),
C++
#include <iostream>
#include <vector>
// Binary search (note boundaries in the caller)
int CeilIndex(std::vector<int> &v, int l, int r, int key) {
while (r-l > 1) {
int m = l + (r-l)/2;
if (v[m] >= key)
r = m;
else
l = m;
}
return r;
}
int LongestIncreasingSubsequenceLength(std::vector<int> &v) {
if (v.size() == 0)
return 0;
std::vector<int> tail(v.size(), 0);
int length = 1; // always points empty slot in tail
tail[0] = v[0];
for (size_t i = 1; i < v.size(); i++) {
if (v[i] < tail[0])
// new smallest value
tail[0] = v[i];
else if (v[i] > tail[length-1])
// v[i] extends largest subsequence
tail[length++] = v[i];
else
// v[i] will become end candidate of an existing subsequence or
// Throw away larger elements in all LIS, to make room for upcoming grater elements t
// (and also, v[i] would have already appeared in one of LIS, identify the location a
tail[CeilIndex(tail, -1, length-1, v[i])] = v[i];
}
return length;
}
int main() {
std::vector<int> v{ 2, 5, 3, 7, 11, 8, 10, 13, 6 };
std::cout << "Length of Longest Increasing Subsequence is " << LongestIncreasingSubsequenceLe
return 0;
1402
Chapter 189. Longest Increasing Subsequence Size (N log N)
Java
1403
Chapter 189. Longest Increasing Subsequence Size (N log N)
Python3
1404
Chapter 189. Longest Increasing Subsequence Size (N log N)
tailTable[0] = A[0]
len = 1
for i in range(1, size):
if (A[i] < tailTable[0]):
# new smallest value
tailTable[0] = A[i]
elif (A[i] > tailTable[len-1]):
# A[i] wants to extend
# largest subsequence
tailTable[len] = A[i]
len+=1
else:
# A[i] wants to be current
# end candidate of an existing
# subsequence. It will replace
# ceil value in tailTable
tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i]
return len
# Driver program to
# test above function
A = [ 2, 5, 3, 7, 11, 8, 10, 13, 6 ]
n =len(A)
print("Length of Longest Increasing Subsequence is ",
LongestIncreasingSubsequenceLength(A, n))
# This code is contributed
# by Anant Agarwal.
C#
1405
Chapter 189. Longest Increasing Subsequence Size (N log N)
// Binary search (note boundaries
// in the caller) A[] is ceilIndex
// in the caller
static int CeilIndex(int []A, int l,
int r, int key)
{
while (r - l > 1)
{
int m = l + (r - l)/2;
if (A[m] >= key)
r = m;
else
l = m;
}
return r;
}
static int LongestIncreasingSubsequenceLength(
int []A, int size)
{
// Add boundary case, when array size
// is one
int []tailTable = new int[size];
int len; // always points empty slot
tailTable[0] = A[0];
len = 1;
for (int i = 1; i < size; i++)
{
if (A[i] < tailTable[0])
// new smallest value
tailTable[0] = A[i];
else if (A[i] > tailTable[len-1])
// A[i] wants to extend largest
// subsequence
tailTable[len++] = A[i];
else
// A[i] wants to be current end
// candidate of an existing
1406
Chapter 189. Longest Increasing Subsequence Size (N log N)
Output:
Complexity:
The loop runs for N elements. In the worst case (what is worst case input?), we may end
up querying ceil value using binary search (log i) for many A[i].
Therefore, T(n) < O( log N! ) = O(N log N). Analyse to ensure that the upper and lower
bounds are also O( N log N ). The complexity is THETA (N log N).
Exercises:
1. Design an algorithm to construct the longest increasing list. Also, model your solution
using DAGs.
2. Design an algorithm to construct all increasing lists of equal longest size.
3. Is the above algorithm an online algorithm?
4. Design an algorithm to construct the longest decreasing list..
— Venki. Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Improved By : nitin mittal
1407
Chapter 189. Longest Increasing Subsequence Size (N log N)
Source
https://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/
1408
Chapter 190
Naive Approach: A normal approach will be to iterate for every element and find out
the longest increasing subsequence. For any particular element, find the length of the
subsequence starting from that element. Print the longest length of the subsequence thus
formed. The time complexity of this approach will be O(n2 ).
Dynamic Programming Approach: Let DP[i] store the length of the longest subse-
quence which ends with A[i]. For every A[i], if A[i]-1 is present in the array before i-th
index, then A[i] will add to the increasing subsequence which has A[i]-1. Hence DP[i] =
DP[ index(A[i]-1) ] + 1. If A[i]-1 is not present in the array before i-th index, then
DP[i]=1 since the A[i] element forms a subsequence which starts with A[i]. Hence the
relation for DP[i] is:
1409
Chapter 190. Longest Increasing consecutive subsequence
else:
DP[i] = 1
1410
Chapter 190. Longest Increasing consecutive subsequence
Output:
Source
https://www.geeksforgeeks.org/longest-increasing-consecutive-subsequence/
1411
Chapter 191
1412
Chapter 191. Longest Palindromic Substring | Set 1
1413
Chapter 191. Longest Palindromic Substring | Set 1
Java
// Java Solution
public class LongestPalinSubstring
{
// A utility function to print a substring str[low..high]
static void printSubStr(String str, int low, int high) {
System.out.println(str.substring(low, high + 1));
}
// This function prints the longest palindrome substring
// of str[].
// It also returns the length of the longest palindrome
static int longestPalSubstr(String str) {
int n = str.length(); // get length of input string
// table[i][j] will be false if substring str[i..j]
// is not palindrome.
// Else table[i][j] will be true
1414
Chapter 191. Longest Palindromic Substring | Set 1
1415
Chapter 191. Longest Palindromic Substring | Set 1
Python
# Python program
import sys
# A utility function to print a
# substring str[low..high]
def printSubStr(st,low,high) :
sys.stdout.write(st[low : high + 1])
sys.stdout.flush()
return ''
# This function prints the longest palindrome
# substring of st[]. It also returns the length
# of the longest palindrome
def longestPalSubstr(st) :
n = len(st) # get length of input string
# table[i][j] will be false if substring
# str[i..j] is not palindrome. Else
# table[i][j] will be true
table = [[0 for x in range(n)] for y
in range(n)]
# All substrings of length 1 are
# palindromes
maxLength = 1
i = 0
while (i < n) :
table[i][i] = True
i = i + 1
# check for sub-string of length 2.
start = 0
i = 0
while i < n - 1 :
1416
Chapter 191. Longest Palindromic Substring | Set 1
Output:
1417
Chapter 191. Longest Palindromic Substring | Set 1
Length is: 10
Source
https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/
1418
Chapter 192
More Examples:
This problem is just the modification of Longest Common Subsequence problem. The idea
1419
Chapter 192. Longest Repeated Subsequence
is to find the LCS(str, str) where str is the input string with the restriction that
when both the characters are same, they shouldn’t be on the same index in the
two strings.
We have discussed a solution to find length of the longest repeated subsequence.
C++
// Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/
// for complete code.
// This function mainly returns LCS(str, str)
// with a condition that same characters at
// same index are not considered.
int findLongestRepeatingSubSeq(string str)
{
int n = str.length();
// Create and initialize DP table
int dp[n+1][n+1];
for (int i=0; i<=n; i++)
for (int j=0; j<=n; j++)
dp[i][j] = 0;
// Fill dp table (similar to LCS loops)
for (int i=1; i<=n; i++)
{
for (int j=1; j<=n; j++)
{
// If characters match and indexes are
// not same
if (str[i-1] == str[j-1] && i != j)
dp[i][j] = 1 + dp[i-1][j-1];
// If characters do not match
else
dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
}
}
return dp[n][n];
}
Python3
1420
Chapter 192. Longest Repeated Subsequence
// Initialize result
string res = "";
1421
Chapter 192. Longest Repeated Subsequence
return res;
1422
Chapter 192. Longest Repeated Subsequence
// THIS PART OF CODE FINDS THE RESULT STRING USING DP[][]
// Initialize result
string res = "";
// Traverse dp[][] from bottom right
int i = n, j = n;
while (i > 0 && j > 0)
{
// If this cell is same as diagonally
// adjacent cell just above it, then
// same characters are present at
// str[i-1] and str[j-1]. Append any
// of them to result.
if (dp[i][j] == dp[i-1][j-1] + 1)
{
res = res + str[i-1];
i--;
j--;
}
// Otherwise we move to the side
// that that gave us maximum result
else if (dp[i][j] == dp[i-1][j])
i--;
else
j--;
}
// Since we traverse dp[][] from bottom,
// we get result in reverse order.
reverse(res.begin(), res.end());
return res;
}
// Driver Program
int main()
{
string str = "AABEBCDD";
cout << longestRepeatedSubSeq(str);
return 0;
}
Python3
1423
Chapter 192. Longest Repeated Subsequence
1424
Chapter 192. Longest Repeated Subsequence
return res
# Driver Program
str = 'AABEBCDD'
print(longestRepeatedSubSeq(str))
# This code is contributed by Soumen Ghosh
Output:
ABD
Source
https://www.geeksforgeeks.org/longest-repeated-subsequence/
1425
Chapter 193
Examples:
1426
Chapter 193. Longest Repeating Subsequence
This problem is just the modification of Longest Common Subsequence problem. The idea
is to find the LCS(str, str)where str is the input string with the restriction that
when both the characters are same, they shouldn’t be on the same index in the
two strings.
Below is the implementation of the idea.
C++
1427
Chapter 193. Longest Repeating Subsequence
}
}
return dp[n][n];
}
// Driver Program
int main()
{
string str = "aabb";
cout << "The length of the largest subsequence that"
" repeats itself is : "
<< findLongestRepeatingSubSeq(str);
return 0;
}
Java
1428
Chapter 193. Longest Repeating Subsequence
// driver program to check above function
public static void main (String[] args)
{
String str = "aabb";
System.out.println("The length of the largest subsequence that"
+" repeats itself is : "+findLongestRepeatingSubSeq(str));
}
}
// This code is contributed by Pramod Kumar
C#
1429
Chapter 193. Longest Repeating Subsequence
// driver program to check above function
public static void Main ()
{
string str = "aabb";
Console.Write("The length of the largest "
+ "subsequence that repeats itself is : "
+ findLongestRepeatingSubSeq(str));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to find the
// longest repeating subsequence
// This function mainly returns
// LCS(str, str) with a condition
// that same characters at same
// index are not considered.
function findLongestRepeatingSubSeq($str)
{
$n = strlen($str);
// Create and initialize
// DP table
$dp = array(array());
for ($i = 0; $i <= $n; $i++)
for ($j = 0; $j <= $n; $j++)
$dp[$i][$j] = 0;
// Fill dp table
// (similar to LCS loops)
for ($i = 1; $i <= $n; $i++)
{
for ($j = 1; $j <= $n; $j++)
{
// If characters match and
// indexes are not same
if ($str[$i - 1] == $str[$j - 1] &&
$i != $j)
$dp[$i][$j] = 1 + $dp[$i - 1][$j - 1];
// If characters
// do not match
1430
Chapter 193. Longest Repeating Subsequence
else
$dp[$i][$j] = max($dp[$i][$j - 1],
$dp[$i - 1][$j]);
}
}
return $dp[$n][$n];
}
// Driver Code
$str = "aabb";
echo "The length of the largest ".
"subsequence that repeats itself is : ",
findLongestRepeatingSubSeq($str);
// This code is contributed
// by shiv_bhakt.
?>
Output:
This article is contributed by Ekta Goel. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above.
Improved By : nitin mittal, shiv_bhakt
Source
https://www.geeksforgeeks.org/longest-repeating-subsequence/
1431
Chapter 194
Examples :
This problem is an extension of longest increasing subsequence problem, but requires more
thinking for finding optimal substructure property in this.
1432
Chapter 194. Longest Zig-Zag Subsequence
We will solve this problem by dynamic Programming method, Let A is given array of
length n of integers. We define a 2D array Z[n][2] such that Z[i][0] contains longest Zig-Zag
subsequence ending at index i and last element is greater than its previous element and
Z[i][1] contains longest Zig-Zag subsequence ending at index i and last element is smaller
than its previous element, then we have following recurrence relation between them,
Recursive Formulation:
Z[i][0] = max (Z[i][0], Z[j][1] + 1);
for all j < i and A[j] < A[i]
Z[i][1] = max (Z[i][1], Z[j][0] + 1);
for all j < i and A[j] > A[i]
The first recurrence relation is based on the fact that, If we are at position i and this
element has to bigger than its previous element then for this sequence (upto i) to be bigger
we will try to choose an element j ( < i) such that A[j] < A[i] i.e. A[j] can become A[i]’s
previous element and Z[j][1] + 1 is bigger than Z[i][0] then we will update Z[i][0].
Remember we have chosen Z[j][1] + 1 not Z[j][0] + 1 to satisfy alternate property because
in Z[j][0] last element is bigger than its previous one and A[i] is greater than A[j] which will
break the alternating property if we update. So above fact derives first recurrence relation,
similar argument can be made for second recurrence relation also.
1433
Chapter 194. Longest Zig-Zag Subsequence
int Z[n][2];
/* Initialize all values from 1 */
for (int i = 0; i < n; i++)
Z[i][0] = Z[i][1] = 1;
int res = 1; // Initialize result
/* Compute values in bottom up manner */
for (int i = 1; i < n; i++)
{
// Consider all elements as previous of arr[i]
for (int j = 0; j < i; j++)
{
// If arr[i] is greater, then check with Z[j][1]
if (arr[j] < arr[i] && Z[i][0] < Z[j][1] + 1)
Z[i][0] = Z[j][1] + 1;
// If arr[i] is smaller, then check with Z[j][0]
if( arr[j] > arr[i] && Z[i][1] < Z[j][0] + 1)
Z[i][1] = Z[j][0] + 1;
}
/* Pick maximum of both values at index i */
if (res < max(Z[i][0], Z[i][1]))
res = max(Z[i][0], Z[i][1]);
}
return res;
}
/* Driver program */
int main()
{
int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 };
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of Longest Zig-Zag subsequence is %d\n",
zzis(arr, n) );
return 0;
}
Java
1434
Chapter 194. Longest Zig-Zag Subsequence
// Function to return longest
// Zig-Zag subsequence length
static int zzis(int arr[], int n)
{
/*Z[i][0] = Length of the longest
Zig-Zag subsequence ending at
index i and last element is
greater than its previous element
Z[i][1] = Length of the longest
Zig-Zag subsequence ending at
index i and last element is
smaller than its previous
element */
int Z[][] = new int[n][2];
/* Initialize all values from 1 */
for (int i = 0; i < n; i++)
Z[i][0] = Z[i][1] = 1;
int res = 1; // Initialize result
/* Compute values in bottom up manner */
for (int i = 1; i < n; i++)
{
// Consider all elements as
// previous of arr[i]
for (int j = 0; j < i; j++)
{
// If arr[i] is greater, then
// check with Z[j][1]
if (arr[j] < arr[i] &&
Z[i][0] < Z[j][1] + 1)
Z[i][0] = Z[j][1] + 1;
// If arr[i] is smaller, then
// check with Z[j][0]
if( arr[j] > arr[i] &&
Z[i][1] < Z[j][0] + 1)
Z[i][1] = Z[j][0] + 1;
}
/* Pick maximum of both values at
index i */
if (res < Math.max(Z[i][0], Z[i][1]))
res = Math.max(Z[i][0], Z[i][1]);
}
1435
Chapter 194. Longest Zig-Zag Subsequence
return res;
}
/* Driver program */
public static void main(String[] args)
{
int arr[] = { 10, 22, 9, 33, 49,
50, 31, 60 };
int n = arr.length;
System.out.println("Length of Longest "+
"Zig-Zag subsequence is " +
zzis(arr, n));
}
}
// This code is contributed by Prerna Saini
C#
1436
Chapter 194. Longest Zig-Zag Subsequence
bottom up manner */
for (int i = 1; i < n; i++)
{
// Consider all elements as
// previous of arr[i]
for (int j = 0; j < i; j++)
{
// If arr[i] is greater, then
// check with Z[j][1]
if (arr[j] < arr[i] &&
Z[i, 0] < Z[j, 1] + 1)
Z[i, 0] = Z[j, 1] + 1;
// If arr[i] is smaller, then
// check with Z[j][0]
if( arr[j] > arr[i] &&
Z[i, 1] < Z[j, 0] + 1)
Z[i, 1] = Z[j, 0] + 1;
}
/* Pick maximum of both values at
index i */
if (res < Math.Max(Z[i, 0], Z[i, 1]))
res = Math.Max(Z[i, 0], Z[i, 1]);
}
return res;
}
// Driver Code
static public void Main ()
{
int []arr = {10, 22, 9, 33,
49, 50, 31, 60};
int n = arr.Length;
Console.WriteLine("Length of Longest "+
"Zig-Zag subsequence is " +
zzis(arr, n));
}
}
// This code is contributed by ajit
PHP
<?php
//PHP program to find longest Zig-Zag
//subsequence in an array
1437
Chapter 194. Longest Zig-Zag Subsequence
// function to return max of two numbers
function maxD($a, $b) {
return ($a > $b) ? $a : $b;
}
// Function to return longest Zig-Zag subsequence length
function zzis($arr, $n)
{
/*Z[i][0] = Length of the longest Zig-Zag subsequence
ending at index i and last element is greater
than its previous element
Z[i][1] = Length of the longest Zig-Zag subsequence
ending at index i and last element is smaller
than its previous element */
//$Z[$n][2];
/* Initialize all values from 1 */
for ($i = 0; $i < $n; $i++)
$Z[$i][0] = $Z[$i][1] = 1;
$res = 1; // Initialize result
/* Compute values in bottom up manner */
for ($i = 1; $i < $n; $i++)
{
// Consider all elements as previous of arr[i]
for ($j = 0; $j < $i; $j++)
{
// If arr[i] is greater, then check with Z[j][1]
if ($arr[$j] < $arr[$i] && $Z[$i][0] < $Z[$j][1] + 1)
$Z[$i][0] = $Z[$j][1] + 1;
// If arr[i] is smaller, then check with Z[j][0]
if( $arr[$j] > $arr[$i] && $Z[$i][1] < $Z[$j][0] + 1)
$Z[$i][1] = $Z[$j][0] + 1;
}
/* Pick maximum of both values at index i */
if ($res < max($Z[$i][0], $Z[$i][1]))
$res = max($Z[$i][0], $Z[$i][1]);
}
return $res;
}
/* Driver program */
1438
Chapter 194. Longest Zig-Zag Subsequence
Output :
Source
https://www.geeksforgeeks.org/longest-zig-zag-subsequence/
1439
Chapter 195
Longest alternating (positive and negative) subarray starting at every index - GeeksforGeeks
A subarray is called alternating if any two consecutive numbers in it have opposite signs (i.e.
one of them should be negative, whereas the other should be positive).
Given an array of n integers. For each index i, we need to find the length if the longest
alternating subarray starting at i.
Examples:
A Naive approach is to use two loops in which we traverse the whole array starting from
every index i (0 to n-1) and calculate the length of the alternating subarray.
Time Complexity: O(n2 ).
1440
Chapter 195. Longest alternating (positive and negative) subarray starting at every index
Efficient Approach:
Observe that when a[i] and a[i+1] have opposite signs, count[i] will be 1 more than
count[i+1]. Otherwise when they have same sign count[i] will be 1.
We use Dynamic Programminghere.
C++
Java
1441
Chapter 195. Longest alternating (positive and negative) subarray starting at every index
public static void longestAlternating(int arr[],
int n)
{
int[] count = new int[n];
// Fill count[] from end.
count[n - 1] = 1;
for (int i = n - 2; i >= 0; i--) {
if (arr[i] * arr[i + 1] < 0)
count[i] = count[i + 1] + 1;
else
count[i] = 1;
}
// Print result
for (int i = 0; i < n; i++)
System.out.print(count[i] + " ");
}
// driver program
public static void main(String[] args)
{
int a[] = { -5, -1, -1, 2, -2, -3 };
int n = 6;
longestAlternating(a, n);
}
}
// This code is contributed by rishabh_jain
Python3
1442
Chapter 195. Longest alternating (positive and negative) subarray starting at every index
i = i - 1
i = 0
# Print result
while i < n :
print (count[i], end = " ")
i = i + 1
# Driver Code
a = [ -5, -1, -1, 2, -2, -3 ]
n = len(a)
longestAlternating(a, n);
# This code is contributed by rishabh_jain
C#
1443
Chapter 195. Longest alternating (positive and negative) subarray starting at every index
{
int []a = { -5, -1, -1, 2, -2, -3 };
int n = 6;
longestAlternating(a, n);
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP program to find longest alternating
// subarray starting from every index.
function longestAlternating( $arr, $n)
{
$count = array();
// Fill count[] from end.
$count[$n - 1] = 1;
for ( $i = $n - 2; $i >= 0; $i--)
{
if ($arr[$i] * $arr[$i + 1] < 0)
$count[$i] = $count[$i + 1] + 1;
else
$count[$i] = 1;
}
// Print result
for ( $i = 0; $i < $n; $i++)
echo $count[$i] , " ";
}
// Driver code
$a = array( -5, -1, -1, 2, -2, -3 );
$n =count($a);
longestAlternating($a, $n);
// This code is contributed by anuj_67.
?>
Output:
1 1 3 2 1 1
Improved By : vt_m
1444
Chapter 195. Longest alternating (positive and negative) subarray starting at every index
Source
https://www.geeksforgeeks.org/longest-alternating-positive-negative-subarray-starting-every-index/
1445
Chapter 196
Longest alternating sub-array starting from every index in a Binary Array - GeeksforGeeks
Given an array containing only 0s and 1s. For each index ‘i‘(0 index), find length of the
longest alternating sub-array starting from ‘i‘ to ‘j‘ i.e., ai..j for i <= j < n. Alternating
sub-array means that any two adjacent elements should be different.
Simple approach is to iterate for every index by using two ‘for loops’ for finding the length
of each index. The outer loop picks a starting point ‘i’ and the inner loop considers all sub-
arrays starting from ‘i’. Time complexity of this approach is O(n2 ) which is not sufficient
for large value of ‘n’.
Better approach is to use Dynamic programming. First of all, let’s see how to check
for alternating sub-array. To check whether two elements are alternating or not, we can
simply take XOR(Ex-OR) of both of them and then compare with ‘0’ and ‘1’.
• If there XOR is ‘0’, that means both numbers are not alternating(equal elements).
1446
Chapter 196. Longest alternating sub-array starting from every index in a Binary Array
Let len[i] denotes length of an alternating sub-array starting at position ‘i’. If arr[i] and
arr[i+1] have different values, then len[i] will be one more than len[i+1]. Otherwise if they
are same elements, len[i] will be just 1.
C++
1447
Chapter 196. Longest alternating sub-array starting from every index in a Binary Array
Java
Python3
1448
Chapter 196. Longest alternating sub-array starting from every index in a Binary Array
# longest alternating
# sub-array for each index elements
# Function to calculate alternating sub-
# array for each index of array elements
def alternateSubarray(arr,n):
len=[]
for i in range(n+1):
len.append(0)
# Initialize the base state of len[]
len[n - 1] = 1
# Calculating value for each element
for i in range(n - 2,-1,-1):
# If both elements are different
# then add 1 to next len[i+1]
if (arr[i] ^ arr[i + 1] == True):
len[i] = len[i + 1] + 1
# else initialize to 1
else:
len[i] = 1
# Print lengths of binary subarrays.
for i in range(n):
print(len[i] , " ",end="")
# Driver code
arr = [ True,False, True, False, False, True ]
n = len(arr)
alternateSubarray(arr, n)
# This code is contributed
# by Anant Agarwal.
C#
1449
Chapter 196. Longest alternating sub-array starting from every index in a Binary Array
class GFG {
// Function to calculate alternating sub-
// array for each index of array elements
static void alternateSubarray(bool []arr,
int n)
{
int []len = new int[n];
// Initialize the base state of len[]
len[n - 1] = 1;
// Calculating value for each element
for (int i = n - 2; i >= 0; --i)
{
// If both elements are different
// then add 1 to next len[i+1]
if (arr[i] ^ arr[i + 1] == true)
len[i] = len[i + 1] + 1;
// else initialize to 1
else
len[i] = 1;
}
// Print lengths of binary subarrays.
for (int i = 0; i < n; ++i)
Console.Write(len[i] + " ");
}
// Driver code
public static void Main()
{
bool []arr = {true, false, true,
false, false, true};
int n = arr.Length;
alternateSubarray(arr, n);
}
}
// This code is contributed by vt_m.
Output :
1450
Chapter 196. Longest alternating sub-array starting from every index in a Binary Array
4 3 2 1 2 1
C++
1451
Chapter 196. Longest alternating sub-array starting from every index in a Binary Array
PHP
<?php
// PHP program to calculate longest alternating
// sub-array for each index elements
// Function to calculate alternating sub-array
// for each index of array elements
function alternateSubarray($arr, $n)
{
// Initialize count variable for storing
// length of sub-array
$count = 1;
// Initialize 'prev' variable which
// indicates the previous element
// while traversing for index 'i'
$prev = $arr[0];
for ($i = 1; $i < $n; ++$i)
{
// If both elements are same
// print elements because alternate
// element is not found for current
// index
if (($arr[$i] ^ $prev) == 0)
{
// print count and decrement it.
while ($count)
echo $count-- , " ";
}
1452
Chapter 196. Longest alternating sub-array starting from every index in a Binary Array
Output :
4 3 2 1 2 1
Source
https://www.geeksforgeeks.org/longest-alternating-sub-array-starting-every-index-binary-array/
1453
Chapter 197
Examples :
This problem is an extension of longest increasing subsequence problem, but requires more
thinking for finding optimal substructure property in this.
We will solve this problem by dynamic Programming method, Let A is given array of length
n of integers. We define a 2D array las[n][2] such that las[i][0] contains longest alternating
1454
Chapter 197. Longest alternating subsequence
subsequence ending at index i and last element is greater than its previous element and
las[i][1] contains longest alternating subsequence ending at index i and last element is smaller
than its previous element, then we have following recurrence relation between them,
Recursive Formulation:
las[i][0] = max (las[i][0], las[j][1] + 1);
for all j < i and A[j] < A[i]
las[i][1] = max (las[i][1], las[j][0] + 1);
for all j < i and A[j] > A[i]
The first recurrence relation is based on the fact that, If we are at position i and this
element has to bigger than its previous element then for this sequence (upto i) to be bigger
we will try to choose an element j ( < i) such that A[j] < A[i] i.e. A[j] can become A[i]’s
previous element and las[j][1] + 1 is bigger than las[i][0] then we will update las[i][0].
Remember we have chosen las[j][1] + 1 not las[j][0] + 1 to satisfy alternate property because
in las[j][0] last element is bigger than its previous one and A[i] is greater than A[j] which
will break the alternating property if we update. So above fact derives first recurrence
relation, similar argument can be made for second recurrence relation also.
1455
Chapter 197. Longest alternating subsequence
Java
1456
Chapter 197. Longest alternating subsequence
1457
Chapter 197. Longest alternating subsequence
/* Driver program */
public static void main(String[] args)
{
int arr[] = { 10, 22, 9, 33, 49,
50, 31, 60 };
int n = arr.length;
System.out.println("Length of Longest "+
"alternating subsequence is " +
zzis(arr, n));
}
}
// This code is contributed by Prerna Saini
C#
1458
Chapter 197. Longest alternating subsequence
bottom up manner */
for (int i = 1; i < n; i++)
{
// Consider all elements as
// previous of arr[i]
for (int j = 0; j < i; j++)
{
// If arr[i] is greater, then
// check with las[j][1]
if (arr[j] < arr[i] &&
las[i, 0] < las[j, 1] + 1)
las[i, 0] = las[j, 1] + 1;
// If arr[i] is smaller, then
// check with las[j][0]
if( arr[j] > arr[i] &&
las[i, 1] < las[j, 0] + 1)
las[i, 1] = las[j, 0] + 1;
}
/* Pick maximum of both
values at index i */
if (res < Math.Max(las[i, 0],
las[i, 1]))
res = Math.Max(las[i, 0],
las[i, 1]);
}
return res;
}
// Driver Code
public static void Main()
{
int []arr = {10, 22, 9, 33,
49, 50, 31, 60};
int n = arr.Length;
Console.WriteLine("Length of Longest "+
"alternating subsequence is " +
zzis(arr, n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
1459
Chapter 197. Longest alternating subsequence
1460
Chapter 197. Longest alternating subsequence
Output :
Source
https://www.geeksforgeeks.org/longest-alternating-subsequence/
1461
Chapter 198
Longest palindrome
subsequence with O(n) space
Examples:
Input : abbaab
Output : 4
Input : geeksforgeeks
Output : 5
1462
Chapter 198. Longest palindrome subsequence with O(n) space
The solution discussed above takes O(n2 ) extra space. In this post a space optimized
solution is discussed that requires O(n) extra space. The idea is to create a one dimensional
array a[] of same size as given string. We make sure that a[i] stores length of longest
palindromic subsequence of prefix ending with i (or substring s[0..i]).
C++
1463
Chapter 198. Longest palindrome subsequence with O(n) space
Java
1464
Chapter 198. Longest palindrome subsequence with O(n) space
// a[i] is going to store length
// of longest palindromic subsequence
// of substring s[0..i]
int a[] = new int[n];
// Pick starting point
for (int i = n - 1; i >= 0; i--)
{
int back_up = 0;
// Pick ending points and see if s[i]
// increases length of longest common
// subsequence ending with s[j].
for (int j = i; j < n; j++) {
// similar to 2D array L[i][j] == 1
// i.e., handling substrings of length
// one.
if (j == i)
a[j] = 1;
// Similar to 2D array L[i][j] = L[i+1][j-1]+2
// i.e., handling case when corner characters
// are same.
else if (s.charAt(i) == s.charAt(j))
{
int temp = a[j];
a[j] = back_up + 2;
back_up = temp;
}
// similar to 2D array L[i][j] = max(L[i][j-1],
// a[i+1][j])
else
{
back_up = a[j];
a[j] = Math.max(a[j - 1], a[j]);
}
}
}
return a[n - 1];
}
/* Driver program to test above functions */
public static void main(String[] args)
{
String str = "GEEKSFORGEEKS";
1465
Chapter 198. Longest palindrome subsequence with O(n) space
System.out.println(lps(str));
}
}
//This article is contributed by prerna saini.
Python3
1466
Chapter 198. Longest palindrome subsequence with O(n) space
else:
back_up = a[j]
a[j] = max(a[j - 1], a[j])
return a[n - 1]
# Driver Code
string = "GEEKSFORGEEKS"
print(lps(string))
# This code is contributed by Ansu Kumari.
C#
1467
Chapter 198. Longest palindrome subsequence with O(n) space
// Similar to 2D array L[i][j] = L[i+1][j-1]+2
// i.e., handling case when corner characters
// are same.
else if (s[i] == s[j])
{
int temp = a[j];
a[j] = back_up + 2;
back_up = temp;
}
// similar to 2D array L[i][j] = max(L[i][j-1],
// a[i+1][j])
else
{
back_up = a[j];
a[j] = Math.Max(a[j - 1], a[j]);
}
}
}
return a[n - 1];
}
// Driver program
public static void Main()
{
string str = "GEEKSFORGEEKS";
Console.WriteLine(lps(str));
}
}
// This code is contributed by vt_m.
PHP
<?php
// A Space optimized Dynamic
// Programming based PHP
// program for LPS problem
// Returns the length of
// the longest palindromic .
// subsequence in str
function lps($s)
{
$n = strlen($s);
// Pick starting point
1468
Chapter 198. Longest palindrome subsequence with O(n) space
1469
Chapter 198. Longest palindrome subsequence with O(n) space
}
}
return $a[$n - 1];
}
// Driver Code
$str = "GEEKSFORGEEKS";
echo lps($str);
// This code is contributed
// by shiv_bhakt.
?>
Source
https://www.geeksforgeeks.org/longest-palindrome-subsequence-space/
1470
Chapter 199
Naive Solution : The problem can be solved easily by taking all the possible substrings
and for all the substrings check it for the remaining(non-overlapping) string if there exists
an identical substring. There are O(n2 ) total substrings and checking them against the
remaining string will take O(n) time. So overall time complexity of above solution is O(n3 ).
1471
Chapter 199. Longest repeating and non-overlapping substring
Dynamic Programming : This problem can be solved in O(n2 ) time using Dynamic
Programming. The basic idea is to find the longest repeating suffix for all prefixes in the
string str.
To avoid overlapping we have to ensure that the length of suffix is less than (j-i) at any
instant.
The maximum value of LCSRe(i, j) provides the length of the longest repeating substring
and the substring itself can be found using the length and the ending index of the common
suffix.
Below is C++ implementation of the recurrence.
1472
Chapter 199. Longest repeating and non-overlapping substring
Output:
geeks
1473
Chapter 199. Longest repeating and non-overlapping substring
Source
https://www.geeksforgeeks.org/longest-repeating-and-non-overlapping-substring/
1474
Chapter 200
1. Find the maximum sum contiguous subarray. Let this sum be maxSum.
2. Find the length of the longest subarray having sum equal to maxSum. Refer this
post.
1475
Chapter 200. Longest subarray having maximum sum
1476
Chapter 200. Longest subarray having maximum sum
}
// required maximum length
return maxLen;
}
// function to find the length of the longest
// subarray having maximum sum
int lenLongSubarrWithMaxSum(int arr[], int n)
{
int maxSum = maxSubArraySum(arr, n);
return lenOfLongSubarrWithGivenSum(arr, n, maxSum);
}
// Driver program to test above
int main()
{
int arr[] = { 5, -2, -1, 3, -4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Length of longest subarray having maximum sum = "
<< lenLongSubarrWithMaxSum(arr, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/longest-subarray-having-maximum-sum/
1477
Chapter 201
This problem is based upon the concept of Longest Increasing Subsequence Problem.
1478
Chapter 201. Longest subsequence such that difference between adjacents is one
C++
1479
Chapter 201. Longest subsequence such that difference between adjacents is one
result = dp[i];
return result;
}
// Driver code
int main()
{
// Longest subsequence with one difference is
// {1, 2, 3, 4, 3, 2}
int arr[] = {1, 2, 3, 4, 5, 3, 2};
int n = sizeof(arr)/sizeof(arr[0]);
cout << longestSubseqWithDiffOne(arr, n);
return 0;
}
Java
1480
Chapter 201. Longest subsequence such that difference between adjacents is one
Python
1481
Chapter 201. Longest subsequence such that difference between adjacents is one
result = 1
for i in range(n):
if (result < dp[i]):
result = dp[i]
return result
# Driver code
arr = [1, 2, 3, 4, 5, 3, 2]
# Longest subsequence with one difference is
# {1, 2, 3, 4, 3, 2}
n = len(arr)
print longestSubseqWithDiffOne(arr, n)
# This code is contributed by Afzal Ansari
C#
1482
Chapter 201. Longest subsequence such that difference between adjacents is one
PHP
<?php
// PHP program to find the longest
// subsequence such the difference
// between adjacent elements of the
// subsequence is one.
// Function to find the length of
// longest subsequence
function longestSubseqWithDiffOne($arr, $n)
{
1483
Chapter 201. Longest subsequence such that difference between adjacents is one
1484
Chapter 201. Longest subsequence such that difference between adjacents is one
$n = sizeof($arr);
echo longestSubseqWithDiffOne($arr, $n);
// This code is contributed by nitin mittal.
?>
Output:
Source
https://www.geeksforgeeks.org/longest-subsequence-such-that-difference-between-adjacents-is-one/
1485
Chapter 202
Lucas Numbers
Input : 3
Output : 4
Input : 7
Output : 29
C/C++
1486
Chapter 202. Lucas Numbers
Java
1487
Chapter 202. Lucas Numbers
// Driver Code
public static void main(String args[])
{
int n = 9;
System.out.println(lucas(n));
}
}
// This code is contributed
// by Nikita Tiwari.
Python3
C#
// Recursive C# program to
// find n'th Lucas number
using System;
class GFG {
// recursive function
public static int lucas(int n)
{
1488
Chapter 202. Lucas Numbers
PHP
<?php
// Recursive php program to
// find n'th Lucas number
// recursive function
function lucas($n)
{
// Base cases
if ($n == 0)
return 2;
if ($n == 1)
return 1;
// recurrence relation
return lucas($n - 1) +
lucas($n - 2);
}
// Driver Code
$n = 9;
echo lucas($n);
// This code is contributed by ajit.
1489
Chapter 202. Lucas Numbers
?>
Output :
76
C/C++
Java
1490
Chapter 202. Lucas Numbers
Pyhton3
1491
Chapter 202. Lucas Numbers
if (n == 0) :
return a
# generating number
for i in range(2, n + 1) :
c = a + b
a = b
b = c
return b
# Driver Code
n = 9
print(lucas(n))
# This code is contributed
# by Nikita tiwari.
C#
// Iterative C# program to
// find n'th Lucas Number
using System;
class GFG {
// Iterative function
static int lucas(int n)
{
// declaring base values
// for positions 0 and 1
int a = 2, b = 1, c, i;
if (n == 0)
return a;
// generating number
for (i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
1492
Chapter 202. Lucas Numbers
PHP
<?php
// Iterative php program
// to find n'th Lucas Number
function lucas($n)
{
// declaring base values
// for positions 0 and 1
$a = 2; $b = 1; $c; $i;
if ($n == 0)
return $a;
// generating number
for ($i = 2; $i <= $n; $i++)
{
$c = $a + $b;
$a = $b;
$b = $c;
}
return $b;
}
// Driver Code
$n = 9;
echo lucas($n);
// This code is contributed by ajit
?>
Output :
76
1493
Chapter 202. Lucas Numbers
References:
https://en.wikipedia.org/wiki/Lucas_number
Improved By : jit_t
Source
https://www.geeksforgeeks.org/lucas-numbers/
1494
Chapter 203
Matrix Exponentiation
1495
Chapter 203. Matrix Exponentiation
C = [a b c
1 0 0
0 1 0]
- - - - 2 times - - -
| F(4) | = | a b c | * | a b c | * | F(2) |
| F(3) | | 1 0 0 | | 1 0 0 | | F(1) |
| F(2) | | 0 1 0 | | 0 1 0 | | F(0) |
- - - - - - - - n -2 times - - - - -
| F(n) | = | a b c | * | a b c | * ... * | a b c | * | F(2) |
| F(n-1) | | 1 0 0 | | 1 0 0 | | 1 0 0 | | F(1) |
| F(n-2) | | 0 1 0 | | 0 1 0 | | 0 1 0 | | F(0) |
1496
Chapter 203. Matrix Exponentiation
| F(n-2) | [ | 0 1 0 | ] | F(0) |
So we can simply multiply our Second matrix n-2 times and then multiply it with the
third matrix to get the result. Multiplication can be done in (log n) time using Divide and
Conquer algorithm for power (See this or this)
Let us consider the problem of finding n’th term of a series defined using below recurrence.
n'th term,
F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3
Base Cases :
F(0) = 0, F(1) = 1, F(2) = 1
1497
Chapter 203. Matrix Exponentiation
mul[i][j] += a[i][k]*b[k][j];
}
}
// storing the muliplication resul in a[][]
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
a[i][j] = mul[i][j]; // Updating our matrix
}
// Function to compute F raise to power n-2.
int power(int F[3][3], int n)
{
int M[3][3] = {{1,1,1}, {1,0,0}, {0,1,0}};
// Multiply it with initial values i.e with
// F(0) = 0, F(1) = 1, F(2) = 1
if (n==1)
return F[0][0] + F[0][1];
power(F, n/2);
multiply(F, F);
if (n%2 != 0)
multiply(F, M);
// Multiply it with initial values i.e with
// F(0) = 0, F(1) = 1, F(2) = 1
return F[0][0] + F[0][1] ;
}
// Return n'th term of a series defined using below
// recurrence relation.
// f(n) is defined as
// f(n) = f(n-1) + f(n-2) + f(n-3), n>=3
// Base Cases :
// f(0) = 0, f(1) = 1, f(2) = 1
int findNthTerm(int n)
{
int F[3][3] = {{1,1,1}, {1,0,0}, {0,1,0}} ;
return power(F, n-2);
}
// Driver code
int main()
{
1498
Chapter 203. Matrix Exponentiation
int n = 5;
cout << "F(5) is " << findNthTerm(n);
return 0;
}
Java
1499
Chapter 203. Matrix Exponentiation
1500
Chapter 203. Matrix Exponentiation
}
//This code is contributed by vt_m.
C#
1501
Chapter 203. Matrix Exponentiation
// Multiply it with initial values i.e
// with F(0) = 0, F(1) = 1, F(2) = 1
if (n == 1)
return F[0, 0] + F[0, 1];
power(F, n / 2);
multiply(F, F);
if (n % 2 != 0)
multiply(F, M);
// Multiply it with initial values i.e
// with F(0) = 0, F(1) = 1, F(2) = 1
return F[0, 0] + F[0, 1];
}
// Return n'th term of a series defined
// using below recurrence relation.
// f(n) is defined as
// f(n) = f(n-1) + f(n-2) + f(n-3), n>=3
// Base Cases :
// f(0) = 0, f(1) = 1, f(2) = 1
static int findNthTerm(int n)
{
int[, ] F = { { 1, 1, 1 }, { 1, 0, 0 },
{ 0, 1, 0 } };
return power(F, n - 2);
}
// Driver code
public static void Main()
{
int n = 5;
Console.WriteLine("F(5) is "
+ findNthTerm(n));
}
}
// This code is contributed by vt_m.
Output :
F(5) is 7
1502
Chapter 203. Matrix Exponentiation
Source
https://www.geeksforgeeks.org/matrix-exponentiation/
1503
Chapter 204
Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i < j < k < l - GeeksforGeeks
Maximize arr[l] – arr[k] + arr[j] – arr[i], such that i < j < k < l. Find the maximum value
of arr[l] – arr[k] + arr[j] – arr[i], such that i < j < k < l
Example:
1504
Chapter 204. Maximize arr[j] – arr[i] + arr[l] – arr[k], such that i < j < k < l
1505
Chapter 204. Maximize arr[j] – arr[i] + arr[l] – arr[k], such that i < j < k < l
Output:
23
Source
https://www.geeksforgeeks.org/maximize-arrj-arri-arrl-arrk-such-that-i-j-k-l/
1506
Chapter 205
1507
Chapter 205. Maximize array elements upto given number
or subtract current array element from value obtained so far from previous elements. Start
from index 0, add or subtract arr[0] from given number and recursively call for next index
along with updated number. When entire array is traversed, compare the updated number
with overall maximum value of number obtained so far.
Below is the implementation of above approach :
C++
1508
Chapter 205. Maximize array elements upto given number
Java
1509
Chapter 205. Maximize array elements upto given number
1510
Chapter 205. Maximize array elements upto given number
Python3
1511
Chapter 205. Maximize array elements upto given number
# def to find maximum possible
# value that can be obtained using
# array elements and given number.
def findMaxVal(arr, n, num, maxLimit) :
global ans
# variable to store
# current index position.
ind = 0
# call to utility def to
# find maximum possible value
# that can be obtained.
findMaxValUtil(arr, n, num, maxLimit, ind)
return ans
# Driver code
num = 1
arr = [3, 10, 6, 4, 5]
n = len(arr)
maxLimit = 15
print (findMaxVal(arr, n, num, maxLimit))
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
1512
Chapter 205. Maximize array elements upto given number
1513
Chapter 205. Maximize array elements upto given number
int n = arr.Length;
int maxLimit = 15;
Console.Write(findMaxVal(arr, n, num,
maxLimit));
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
PHP
<?php
// PHP code to find maximum
// value of number obtained by
// using array elements recursively.
// Utility function to find
// maximum possible value
function findMaxValUtil($arr, $n,
$num, $maxLimit,
$ind, &$ans)
{
// If entire array is traversed,
// then compare current value
// in num to overall maximum
// obtained so far.
if ($ind == $n)
{
$ans = max($ans, $num);
return;
}
// Case 1: Subtract current element
// from value so far if result is
// greater than or equal to zero.
if ($num - $arr[$ind] >= 0)
{
findMaxValUtil($arr, $n,
$num - $arr[$ind],
$maxLimit, $ind + 1,
$ans);
}
// Case 2 : Add current element to
// value so far if result is less
// than or equal to maxLimit.
1514
Chapter 205. Maximize array elements upto given number
Output:
1515
Chapter 205. Maximize array elements upto given number
A boolean DP table can be created in which dp[i][j] is 1 if value j can be obtained using
arr[0..i] and 0 if not. For each index position, start from j = 0 and move to value maxLimit,
and set dp[i][j] either 0 or 1 as described above. Find the maximum possible value that can
be obtained at index position n-1 by finding maximum j when i = n-1 and dp[n-1][j] = 1.
C++
1516
Chapter 205. Maximize array elements upto given number
1517
Chapter 205. Maximize array elements upto given number
dp[ind][val] = dp[ind-1][val+arr[ind]];
}
else
{
dp[ind][val] = 0;
}
}
}
}
// Find maximum value that is obtained
// at index n-1.
for(val = maxLimit; val >= 0; val--)
{
if(dp[n-1][val])
{
return val;
}
}
// If no solution exists return -1.
return -1;
}
// Driver Code
int main()
{
int num = 1;
int arr[] = {3, 10, 6, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int maxLimit = 15;
cout << findMaxVal(arr, n, num, maxLimit);
return 0;
}
Java
1518
Chapter 205. Maximize array elements upto given number
1519
Chapter 205. Maximize array elements upto given number
1520
Chapter 205. Maximize array elements upto given number
// If no solution
// exists return -1.
return -1;
}
// Driver Code
public static void main(String args[])
{
int num = 1;
int []arr = new int[]{3, 10, 6, 4, 5};
int n = arr.length;
int maxLimit = 15;
System.out.print(findMaxVal(arr, n,
num, maxLimit));
}
}
// This code is contributed
// by Manish Shaw(manishshaw1)
C#
1521
Chapter 205. Maximize array elements upto given number
1522
Chapter 205. Maximize array elements upto given number
}
else if(val - arr[ind] >= 0)
{
dp[ind,val] = dp[ind-1,val-arr[ind]];
}
else if(val + arr[ind] <= maxLimit)
{
dp[ind,val] = dp[ind-1,val+arr[ind]];
}
else
{
dp[ind,val] = 0;
}
}
}
}
// Find maximum value that is obtained
// at index n-1.
for(val = maxLimit; val >= 0; val--)
{
if(dp[n-1,val] == 1)
{
return val;
}
}
// If no solution exists return -1.
return -1;
}
// Driver Code
static void Main()
{
int num = 1;
int []arr = new int[]{3, 10, 6, 4, 5};
int n = arr.Length;
int maxLimit = 15;
Console.Write(
findMaxVal(arr, n, num, maxLimit));
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
Output:
1523
Chapter 205. Maximize array elements upto given number
Time Complexity : O(n*maxLimit), where n is the size of array and maxLimit is the
given max value.
Auxiliary Space : O(n*maxLimit), n is the size of array and maxLimit is the given max
value.
Optimization : The space required can be reduced to O(2*maxLimit). Note that at every
index position, we are only using values from previous row. So we can create a table with
two rows, in which one of the rows store result for previous iteration and other for the
current iteration.
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/maximize-array-elements-upto-given-number/
1524
Chapter 206
Input : R = 3, C =3
mat[][] = { 0, 0, 1,
0, 0, 1,
1, 0, 1 }
Output : 8
Flip
0 0 1
0 0 1
1 0 1
to get
1 1 1
1 1 1
0 1 1
Input : R = 2, C = 3
mat[][] = { 0, 0, 0,
0, 0, 0 }
Output : 6
1525
Chapter 206. Maximize the binary matrix by filpping submatrix once
Create a matrix ones[][] of R rows and C columns, which precomputes the number of ones
in the submatrix from (0, 0) to (i, j) by
Since, we are allowed to flip sub matrix only once. We iterate over all possible submatrices
of all possible sizes for each cell (i, j) to (i + k – 1, i + k – 1). We calculate the total number
of ones after the digits are filliped in the chosen submatrix.
Total number of ones in the final matrix after flipping submatrix (i, j) to (i + k – 1) will
be Ones in the whole matrix – Ones in the chosen submatrix + Zeroes in the chosen sub
matrix. That comes out to be :-
ones[R][C] – cal(i, j, i + k, j + k – 1) + k*k – cal(i, j, i + k – 1, j + k – 1)
where cal(a, b, c, d) denotes the number of ones in square submatrix of length c – a.
Now cal(x1, y1, x2, y2) can be define by:
ones[x2][y2] – ones[x2][y1 – 1] – ones[x1 – 1][y2] + ones[x1 – 1][y1 – 1].
Below is the C++ implementation of this approach:
1526
Chapter 206. Maximize the binary matrix by filpping submatrix once
ones[i - 1][j - 1] +
(mat[i - 1][j - 1] == 1);
// Finding the maximum number of 1s after flipping
for (int k = 1; k <= min(R, C); k++)
for (int i = 1; i + k - 1 <= R; i++)
for (int j = 1; j + k - 1 <= C; j++)
ans = max(ans, (ones[R][C] + k * k -
2 * cal(ones, i, j, k)));
return ans;
}
// Driver code
int main()
{
int mat[R][C] = {{0, 0, 1},
{ 0, 0, 1},
{ 1, 0, 1 }
};
cout << sol(mat) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/maximize-binary-matrix-filpping-submatrix/
1527
Chapter 207
Maximize the sum of selected numbers from an array to make it empty - GeeksforGeeks
Given an array of N numbers, we need to maximize the sum of selected numbers. At each
step you need to select a number Ai , delete one occurrence of Ai -1 (if exists), Ai +1 (if
exists) and Ai each from the array. Repeat these steps until the array gets empty. The
problem is to maximize the sum of selected numbers.
Note: We have to delete Ai +1 and Ai -1 elements if they are present in the array and not
Ai+1 and Ai-1 .
Examples:
1528
Chapter 207. Maximize the sum of selected numbers from an array to make it empty
Our aim is to maximize the sum of selected numbers. The idea is to pre-calculate the
occurrence of all numbers x in the array a[] in a hash ans. Now our recurrence relation will
decide either to select a number or not. If we select the number then we take the occurrences
of that number and the value stored at ans[i-2] as ans[i-1] will be deleted and not be taken to
count. If we do not select the number then we take ans[i-1] which have been pre-calculated
while moving forward.
At the end, ans[maximum] will have the maximum sum of selected numbers.
Below is the implementation of above idea:
1529
Chapter 207. Maximize the sum of selected numbers from an array to make it empty
Output:
Time Complexity: O(Amax ), where Amax is the maximum element present in the array
A[].
Source
https://www.geeksforgeeks.org/maximize-sum-selected-numbers-performing-following-operation/
1530
Chapter 208
We have discussed this problem in Maximum Product Subarray, but there is a restriction
that result can only be positive. For maximum product to be negative or zero, the values of
variable maxval (maximum product upto current element) and minval (minimum product
upto current element), has to be updated as follows:
1. When arr[i] is positive: As maxval is maximum possible value, simply multiply arr[i]
with maxval to obtain new maxval. minval is minimum possible negative product. If
its previous value is negative then simply multiply it with arr[i]. If its value is 1 keep
it as 1.
2. When arr[i] is 0: Update maxval with zero in case all other elements are negative
then this is the maximum possible product so far. Update minval with 1 as subarray
product with zero as element in it will be zero, which is not minimum. So to include
next element exclude this zero from minval by setting it to 1, i.e., restarting product
calculation.
1531
Chapter 208. Maximum Product Subarray | Added negative product case
3. When arr[i] is negative: new value of maxval is previous minval*arr[i] and new value
of minval is previous maxval*arr[i]. Before updating maxval, store its previous value
in prevMax to be used to update minval.
Implementation:
1532
Chapter 208. Maximum Product Subarray | Added negative product case
else if (arr[i] == 0) {
minval = 1;
maxval = 0;
}
// If current element is negative, then new
// value of maxval is previous minval*arr[i]
// and new value of minval is previous
// maxval*arr[i]. Before updating maxval,
// store its previous value in prevMax to
// be used to update minval.
else if (arr[i] < 0) {
prevMax = maxval;
maxval = minval * arr[i];
minval = prevMax * arr[i];
}
// Update ans if necessary.
ans = max(ans, maxval);
// If maxval is zero, then to calculate
// product for next iteration, it should
// be set to 1 as maximum product
// subarray does not include 0.
// The minimum possible value
// to be considered in maximum product
// subarray is already stored in minval,
// so when maxval is negative it is set to 1.
if (maxval <= 0) {
maxval = 1;
}
}
return ans;
}
int main()
{
int arr[] = { 0, -4, 0, -2 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findMaxProduct(arr, n);
return 0;
}
Output: 0
1533
Chapter 208. Maximum Product Subarray | Added negative product case
Source
https://www.geeksforgeeks.org/maximum-product-subarray-added-negative-product-case/
1534
Chapter 209
1535
Chapter 209. Maximum Subarray Sum Excluding Certain Elements
Now, in this problem when we consider any element, we check by linearly searchingin the
array B, if that element is present in B then we set curr_max to zero which means that
at that index all subarrays we considered upto that point would end and not be extended
further as no further contiguous arrays can be formed, i.e
If the current element of array A is not part of array B, we proceed with the Kadane’s
Algorithm and keep track of the max_so_far.
C++
1536
Chapter 209. Maximum Subarray Sum Excluding Certain Elements
1537
Chapter 209. Maximum Subarray Sum Excluding Certain Elements
Java
1538
Chapter 209. Maximum Subarray Sum Excluding Certain Elements
return max_so_far;
}
// Wrapper for findMaxSubarraySumUtil()
static void findMaxSubarraySum(int A[], int B[],
int n, int m)
{
int maxSubarraySum = findMaxSubarraySumUtil(A, B,
n, m);
// This case will occour when all
// elements of A are are present
// in B, thus no subarray can be formed
if (maxSubarraySum == -2147483648) {
System.out.println("Maximum Subarray Sum"
+ " " + "can't be found");
}
else {
System.out.println("The Maximum Subarray Sum = "
+ maxSubarraySum);
}
}
// Driver code
public static void main(String[] args)
{
int A[] = { 3, 4, 5, -4, 6 };
int B[] = { 1, 8, 5 };
int n = A.length;
int m = B.length;
// Calling Function
findMaxSubarraySum(A, B, n, m);
}
}
// This code is contributed by Ajit.
C#
1539
Chapter 209. Maximum Subarray Sum Excluding Certain Elements
// Function to check the element
// present in array B
static bool isPresent(int[] B, int m,
int x)
{
for (int i = 0; i < m; i++)
if (B[i] == x)
return true;
return false;
}
// Utility function for findMaxSubarraySum()
// with the following parameters
// A => Array A,
// B => Array B,
// n => Number of elements in Array A,
// m => Number of elements in Array B
static int findMaxSubarraySumUtil(int[] A, int[] B,
int n, int m)
{
// set max_so_far to INT_MIN
int max_so_far = -2147483648, curr_max = 0;
for (int i = 0; i < n; i++) {
// if the element is present in B,
// set current max to 0 and move to
// the next element
if (isPresent(B, m, A[i])) {
curr_max = 0;
continue;
}
// Proceed as in Kadane's Algorithm
curr_max = Math.Max(A[i], curr_max + A[i]);
max_so_far = Math.Max(max_so_far, curr_max);
}
return max_so_far;
}
// Wrapper for findMaxSubarraySumUtil()
static void findMaxSubarraySum(int[] A, int[] B,
int n, int m)
{
int maxSubarraySum = findMaxSubarraySumUtil(A, B,
1540
Chapter 209. Maximum Subarray Sum Excluding Certain Elements
n, m);
// This case will occour when all
// elements of A are are present
// in B, thus no subarray can be formed
if (maxSubarraySum == -2147483648)
{
Console.Write("Maximum Subarray Sum"
+ " " + "can't be found");
}
else
{
Console.Write("The Maximum Subarray Sum = "
+ maxSubarraySum);
}
}
// Driver Code
static public void Main ()
{
int[] A = {3, 4, 5, -4, 6};
int[] B = {1, 8, 5};
int n = A.Length;
int m = B.Length;
// Calling Function
findMaxSubarraySum(A, B, n, m);
}
}
// This code is contributed by Shrikant13.
PHP
<?php
// PHP Program to find max subarray
// sum excluding some elements
// Function to check the element
// present in array B
function isPresent($B, $m, $x)
{
for ($i = 0; $i < $m; $i++)
if ($B[$i] == $x)
1541
Chapter 209. Maximum Subarray Sum Excluding Certain Elements
return true;
return false;
}
// Utility function for
// findMaxSubarraySum()
// with the following
// parameters
// A => Array A,
// B => Array B,
// n => Number of elements
// in Array A,
// m => Number of elements
// in Array B
function findMaxSubarraySumUtil($A, $B,
$n, $m)
{
// set max_so_far
// to INT_MIN
$max_so_far = PHP_INT_MIN;
$curr_max = 0;
for ($i = 0; $i < $n; $i++)
{
// if the element is present
// in B, set current max to
// 0 and move to the next
// element
if (isPresent($B, $m, $A[$i]))
{
$curr_max = 0;
continue;
}
// Proceed as in
// Kadane's Algorithm
$curr_max = max($A[$i],
$curr_max + $A[$i]);
$max_so_far = max($max_so_far,
$curr_max);
}
return $max_so_far;
}
// Wrapper for
// findMaxSubarraySumUtil()
1542
Chapter 209. Maximum Subarray Sum Excluding Certain Elements
Output :
1543
Chapter 209. Maximum Subarray Sum Excluding Certain Elements
Search
Note: We need to sort the Array B to apply Binary Search on it.
C++
1544
Chapter 209. Maximum Subarray Sum Excluding Certain Elements
// This case will occour when all elements
// of A are present in B, thus no subarray
// can be formed
if (maxSubarraySum == INT_MIN) {
cout << "Maximum subarray sum cant be found"
<< endl;
}
else {
cout << "The Maximum subarray sum = "
<< maxSubarraySum << endl;
}
}
// Driver Code
int main()
{
int A[] = { 3, 4, 5, -4, 6 };
int B[] = { 1, 8, 5 };
int n = sizeof(A) / sizeof(A[0]);
int m = sizeof(B) / sizeof(B[0]);
// Calling fucntion
findMaxSubarraySum(A, B, n, m);
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/maximum-subarray-sum-excluding-certain-elements/
1545
Chapter 210
C++
// A Divide and Conquer based program for maximum subarray sum problem
#include <stdio.h>
1546
Chapter 210. Maximum Subarray Sum using Divide and Conquer algorithm
#include <limits.h>
// A utility funtion to find maximum of two integers
int max(int a, int b) { return (a > b)? a : b; }
// A utility funtion to find maximum of three integers
int max(int a, int b, int c) { return max(max(a, b), c); }
// Find the maximum possible sum in arr[] auch that arr[m] is part of it
int maxCrossingSum(int arr[], int l, int m, int h)
{
// Include elements on left of mid.
int sum = 0;
int left_sum = INT_MIN;
for (int i = m; i >= l; i--)
{
sum = sum + arr[i];
if (sum > left_sum)
left_sum = sum;
}
// Include elements on right of mid
sum = 0;
int right_sum = INT_MIN;
for (int i = m+1; i <= h; i++)
{
sum = sum + arr[i];
if (sum > right_sum)
right_sum = sum;
}
// Return sum of elements on left and right of mid
return left_sum + right_sum;
}
// Returns sum of maxium sum subarray in aa[l..h]
int maxSubArraySum(int arr[], int l, int h)
{
// Base Case: Only one element
if (l == h)
return arr[l];
// Find middle point
int m = (l + h)/2;
/* Return maximum of following three possible cases
a) Maximum subarray sum in left half
b) Maximum subarray sum in right half
1547
Chapter 210. Maximum Subarray Sum using Divide and Conquer algorithm
c) Maximum subarray sum such that the subarray crosses the midpoint */
return max(maxSubArraySum(arr, l, m),
maxSubArraySum(arr, m+1, h),
maxCrossingSum(arr, l, m, h));
}
/*Driver program to test maxSubArraySum*/
int main()
{
int arr[] = {2, 3, 4, 5, 7};
int n = sizeof(arr)/sizeof(arr[0]);
int max_sum = maxSubArraySum(arr, 0, n-1);
printf("Maximum contiguous sum is %dn", max_sum);
getchar();
return 0;
}
Java
1548
Chapter 210. Maximum Subarray Sum using Divide and Conquer algorithm
right_sum = sum;
}
// Return sum of elements on left
// and right of mid
return left_sum + right_sum;
}
// Returns sum of maxium sum subarray
// in aa[l..h]
static int maxSubArraySum(int arr[], int l,
int h)
{
// Base Case: Only one element
if (l == h)
return arr[l];
// Find middle point
int m = (l + h)/2;
/* Return maximum of following three
possible cases:
a) Maximum subarray sum in left half
b) Maximum subarray sum in right half
c) Maximum subarray sum such that the
subarray crosses the midpoint */
return Math.max(Math.max(maxSubArraySum(arr, l, m),
maxSubArraySum(arr, m+1, h)),
maxCrossingSum(arr, l, m, h));
}
/* Driver program to test maxSubArraySum */
public static void main(String[] args)
{
int arr[] = {2, 3, 4, 5, 7};
int n = arr.length;
int max_sum = maxSubArraySum(arr, 0, n-1);
System.out.println("Maximum contiguous sum is "+
max_sum);
}
}
// This code is contributed by Prerna Saini
Python3
1549
Chapter 210. Maximum Subarray Sum using Divide and Conquer algorithm
# Find the maximum possible sum in
# arr[] auch that arr[m] is part of it
def maxCrossingSum(arr, l, m, h) :
# Include elements on left of mid.
sm = 0; left_sum = -10000
for i in range(m, l-1, -1) :
sm = sm + arr[i]
if (sm > left_sum) :
left_sum = sm
# Include elements on right of mid
sm = 0; right_sum = -1000
for i in range(m + 1, h + 1) :
sm = sm + arr[i]
if (sm > right_sum) :
right_sum = sm
# Return sum of elements on left and right of mid
return left_sum + right_sum;
# Returns sum of maxium sum subarray in aa[l..h]
def maxSubArraySum(arr, l, h) :
# Base Case: Only one element
if (l == h) :
return arr[l]
# Find middle point
m = (l + h) // 2
# Return maximum of following three possible cases
# a) Maximum subarray sum in left half
# b) Maximum subarray sum in right half
# c) Maximum subarray sum such that the
# subarray crosses the midpoint
return max(maxSubArraySum(arr, l, m),
maxSubArraySum(arr, m+1, h),
maxCrossingSum(arr, l, m, h))
1550
Chapter 210. Maximum Subarray Sum using Divide and Conquer algorithm
# Driver Code
arr = [2, 3, 4, 5, 7]
n = len(arr)
max_sum = maxSubArraySum(arr, 0, n-1)
print("Maximum contiguous sum is ", max_sum)
# This code is contributed by Nikita Tiwari.
C#
1551
Chapter 210. Maximum Subarray Sum using Divide and Conquer algorithm
Output :
1552
Chapter 210. Maximum Subarray Sum using Divide and Conquer algorithm
Tree method or Master method. It falls in case II of Master Method and solution of the
recurrence is Θ(nLogn).
The Kadane’s Algorithm for this problem takes O(n) time. Therefore the Kadane’s algo-
rithm is better than the Divide and Conquer approach, but this problem can be considered
as a good example to show power of Divide and Conquer. The above simple approach where
we divide the array in two halves, reduces the time complexity from O(n^2) to O(nLogn).
References:
Introduction to Algorithms by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson,
Ronald L.
Source
https://www.geeksforgeeks.org/maximum-subarray-sum-using-divide-and-conquer-algorithm/
1553
Chapter 211
MSDS[i] = a[i] + max( MSDS[j] ) where i > j > 0 and arr[j] > arr[i] or,
MSDS[i] = a[i], if no such j exists.
To find the MSDS for a given array, we need to return max(MSDS[i]) where n > i > 0.
Below is the implementation of the above approach:
C++
1554
Chapter 211. Maximum Sum Decreasing Subsequence
Java
1555
Chapter 211. Maximum Sum Decreasing Subsequence
1556
Chapter 211. Maximum Sum Decreasing Subsequence
C#
1557
Chapter 211. Maximum Sum Decreasing Subsequence
int n = 7;
Console.WriteLine("Sum of maximum sum" +
" decreasing subsequence is: " +
maxSumDS(arr, n));
}
}
// This code is contributed by m_kit
PHP
<?php
// PHP code to return the maximum sum
// of decreasing subsequence in arr[]
// function to return the maximum
// sum of decreasing subsequence
// in arr[]
function maxSumDS($arr, $n)
{
$i; $j; $max = 0;
$MSDS = array();
// Initialize msds values
// for all indexes
for ($i = 0; $i < $n; $i++)
$MSDS[$i] = $arr[$i];
// Compute maximum sum values
// in bottom up manner
for ($i = 1; $i < $n; $i++)
for ($j = 0; $j < $i; $j++)
if ($arr[$i] < $arr[$j] &&
$MSDS[$i] < $MSDS[$j] + $arr[$i])
$MSDS[$i] = $MSDS[$j] + $arr[$i];
// Pick maximum of
// all msds values
for ($i = 0; $i < $n; $i++)
if ($max < $MSDS[$i])
$max = $MSDS[$i];
return $max;
}
// Driver Code
$arr = array (5, 4, 100,
3, 2, 101, 1 );
1558
Chapter 211. Maximum Sum Decreasing Subsequence
$n = sizeof($arr);
echo "Sum of maximum sum decreasing " .
"subsequence is: ",
maxSumDS($arr, $n);
// This code is contributed by ajit
?>
Output:
Source
https://www.geeksforgeeks.org/maximum-sum-decreasing-subsequence/
1559
Chapter 212
1560
Chapter 212. Maximum absolute difference between sum of two contiguous sub-arrays
We can build above four arrays in O(n) time by using Kadane Algorithm.
In order to calculate maximum sum subarray that lies in arr[0…i], we run Kadane Algorithm
from 0 to n-1 and to find maximum sum subarray that lies in arr[i+1 … n-1], we run Kadane
Algorithm from n-1 to 0.
Kadane’s algorithm can be modified to find minimum absolute sum of a subarray as well.
The idea is to change the sign of each element in the array and run Kadane Algorithm to
find maximum sum subarray that lies in arr[0…i] and arr[i+1 … n-1]. Now invert the sign
of maximum subarray sum found. That will be our minimum subarray sum. This idea is
taken from here.
Now from above four arrays, we can easily find maximum absolute difference between the
sum of two contiguous sub-arrays. For each index i, take maximum of
1. abs(max sum subarray that lies in arr[0…i] – min sum subarray that lies in arr[i+1…n-
1])
2. abs(min sum subarray that lies in arr[0…i] – max sum subarray that lies in arr[i+1…n-
1])
C++
1561
Chapter 212. Maximum absolute difference between sum of two contiguous sub-arrays
1562
Chapter 212. Maximum absolute difference between sum of two contiguous sub-arrays
1563
Chapter 212. Maximum absolute difference between sum of two contiguous sub-arrays
Java
1564
Chapter 212. Maximum absolute difference between sum of two contiguous sub-arrays
return max_so_far;
}
// The function finds two non-overlapping contiguous
// sub-arrays such that the absolute difference
// between the sum of two sub-array is maximum.
static int findMaxAbsDiff(int arr[], int n)
{
// create and build an array that stores
// maximum sums of subarrays that lie in
// arr[0...i]
int leftMax[] = new int[n];
maxLeftSubArraySum(arr, n, leftMax);
// create and build an array that stores
// maximum sums of subarrays that lie in
// arr[i+1...n-1]
int rightMax[] = new int[n];
maxRightSubArraySum(arr, n - 1, rightMax);
// Invert array (change sign) to find minumum
// sum subarrays.
int invertArr[] = new int[n];
for (int i = 0; i < n; i++)
invertArr[i] = -arr[i];
// create and build an array that stores
// minimum sums of subarrays that lie in
// arr[0...i]
int leftMin[] = new int[n];
maxLeftSubArraySum(invertArr, n, leftMin);
for (int i = 0; i < n; i++)
leftMin[i] = -leftMin[i];
// create and build an array that stores
// minimum sums of subarrays that lie in
// arr[i+1...n-1]
int rightMin[] = new int[n];
maxRightSubArraySum(invertArr, n - 1, rightMin);
for (int i = 0; i < n; i++)
rightMin[i] = -rightMin[i];
int result = -2147483648;
for (int i = 0; i < n - 1; i++) {
/* For each index i, take maximum of
1. abs(max sum subarray that lies in arr[0...i] -
1565
Chapter 212. Maximum absolute difference between sum of two contiguous sub-arrays
Python3
# Python3 program to find two non-
# overlapping contiguous sub-arrays
# such that the absolute difference
# between the sum of two sub-array is maximum.
# Find maximum subarray sum for
# subarray [0..i] using standard
# Kadane's algorithm. This version
# of Kadane's Algorithm will work if
# all numbers are negative.
def maxLeftSubArraySum(a, size, sum):
max_so_far = a[0]
curr_max = a[0]
sum[0] = max_so_far
for i in range(1, size):
curr_max = max(a[i], curr_max + a[i])
max_so_far = max(max_so_far, curr_max)
sum[i] = max_so_far
1566
Chapter 212. Maximum absolute difference between sum of two contiguous sub-arrays
return max_so_far
# Find maximum subarray sum for
# subarray [i..n] using Kadane's
# algorithm. This version of Kadane's
# Algorithm will work if all numbers are negative
def maxRightSubArraySum(a, n, sum):
max_so_far = a[n]
curr_max = a[n]
sum[n] = max_so_far
for i in range(n - 1, -1, -1):
curr_max = max(a[i], curr_max + a[i])
max_so_far = max(max_so_far, curr_max)
sum[i] = max_so_far
return max_so_far
# The function finds two non-overlapping
# contiguous sub-arrays such that the
# absolute difference between the sum
# of two sub-array is maximum.
def findMaxAbsDiff(arr, n):
# create and build an array that
# stores maximum sums of subarrays
# that lie in arr[0...i]
leftMax = [0 for i in range(n)]
maxLeftSubArraySum(arr, n, leftMax)
# create and build an array that stores
# maximum sums of subarrays that lie in
# arr[i+1...n-1]
rightMax = [0 for i in range(n)]
maxRightSubArraySum(arr, n-1, rightMax)
# Invert array (change sign) to
# find minumum sum subarrays.
invertArr = [0 for i in range(n)]
for i in range(n):
invertArr[i] = -arr[i]
# create and build an array that stores
# minimum sums of subarrays that lie in
# arr[0...i]
leftMin = [0 for i in range(n)]
1567
Chapter 212. Maximum absolute difference between sum of two contiguous sub-arrays
maxLeftSubArraySum(invertArr, n, leftMin)
for i in range(n):
leftMin[i] = -leftMin[i]
# create and build an array that stores
# minimum sums of subarrays that lie in
# arr[i+1...n-1]
rightMin = [0 for i in range(n)]
maxRightSubArraySum(invertArr, n - 1, rightMin)
for i in range(n):
rightMin[i] = -rightMin[i]
result = -2147483648
for i in range(n - 1):
''' For each index i, take maximum of
1. abs(max sum subarray that lies in arr[0...i] -
min sum subarray that lies in arr[i+1...n-1])
2. abs(min sum subarray that lies in arr[0...i] -
max sum subarray that lies in arr[i+1...n-1]) '''
absValue = max(abs(leftMax[i] - rightMin[i + 1]),
abs(leftMin[i] - rightMax[i + 1]))
if (absValue > result):
result = absValue
return result
# Driver Code
a = [-2, -3, 4, -1, -2, 1, 5, -3]
n = len(a)
print(findMaxAbsDiff(a, n))
# This code is contributed by Anant Agarwal.
C#
1568
Chapter 212. Maximum absolute difference between sum of two contiguous sub-arrays
{
int max_so_far = a[0];
int curr_max = a[0];
sum[0] = max_so_far;
for (int i = 1; i < size; i++)
{
curr_max = Math.Max(a[i], curr_max + a[i]);
max_so_far = Math.Max(max_so_far, curr_max);
sum[i] = max_so_far;
}
return max_so_far;
}
// Find maximum subarray sum for subarray
// [i..n] using Kadane's algorithm.
// This version of Kadane's Algorithm will
// work if all numbers are negative
static int maxRightSubArraySum(int []a, int n,
int []sum)
{
int max_so_far = a[n];
int curr_max = a[n];
sum[n] = max_so_far;
for (int i = n-1; i >= 0; i--)
{
curr_max = Math.Max(a[i], curr_max + a[i]);
max_so_far = Math.Max(max_so_far, curr_max);
sum[i] = max_so_far;
}
return max_so_far;
}
// The function finds two non-overlapping
// contiguous sub-arrays such that the
// absolute difference between the sum
// of two sub-array is maximum.
static int findMaxAbsDiff(int []arr, int n)
{
// create and build an array that stores
// maximum sums of subarrays that lie in
// arr[0...i]
int []leftMax=new int[n];
maxLeftSubArraySum(arr, n, leftMax);
1569
Chapter 212. Maximum absolute difference between sum of two contiguous sub-arrays
1570
Chapter 212. Maximum absolute difference between sum of two contiguous sub-arrays
Output :
12
Time Complexity is O(n) where n is the number of elements in input array. Auxiliary Space
required is O(n).
Source
https://www.geeksforgeeks.org/maximum-absolute-difference-between-sum-of-two-contiguous-sub-arrays/
1571
Chapter 213
Consstraint :
n <= 50
m <= 50
-50 <= x1, x2, .. xn <= 50
Examples :
Input : n = 2, m = 2
arr[] = {1, 2, 3, 4}
Output : Maximum : 25
Minimum : 21
The expression is (x1 + x2) * (y1 + y2) and
the given integers are 1, 2, 3 and 4. Then
maximum value is (1 + 4) * (2 + 3) = 25
whereas minimum value is (4 + 3) * (2 + 1)
= 21.
Input : n = 3, m = 1
arr[] = {1, 2, 3, 4}
Output : Maximum : 24
Minimum : 9
1572
Chapter 213. Maximum and Minimum Values of an Algebraic Expression
C++
1573
Chapter 213. Maximum and Minimum Values of an Algebraic Expression
// initialize the dp array to 01
memset(dp, 0, sizeof(dp));
dp[0][0] = 1;
// if dp[i][j] is true, that means
// it is possible to select i numbers
// from (n + m) numbers to sum upto j
for (int i = 0; i < (n + m); i++) {
// k can be at max n because the
// left expression has n numbers
for (int k = min(n, i + 1); k >= 1; k--) {
for (int j = 0; j < MAX * MAX + 1; j++) {
if (dp[k - 1][j])
dp[k][j + arr[i]] = 1;
}
}
}
int max_value = -INF, min_value = INF;
for (int i = 0; i < MAX * MAX + 1; i++) {
// checking if a particular sum
// can be reachable by choosing
// n numbers
if (dp[n][i]) {
// getting the actual sum as
// we shifted the numbers by
/// 50 to avoid negative indexing
// in array
int temp = i - 50 * n;
max_value = max(max_value, temp * (sum - temp));
min_value = min(min_value, temp * (sum - temp));
}
}
cout << "Maximum Value: " << max_value
<< "\n"
<< "Minimum Value: "
<< min_value << endl;
}
// Driver Code
int main()
{
1574
Chapter 213. Maximum and Minimum Values of an Algebraic Expression
int n = 2, m = 2;
int arr[] = { 1, 2, 3, 4 };
minMaxValues(arr, n, m);
return 0;
}
Java
1575
Chapter 213. Maximum and Minimum Values of an Algebraic Expression
1576
Chapter 213. Maximum and Minimum Values of an Algebraic Expression
Python3
1577
Chapter 213. Maximum and Minimum Values of an Algebraic Expression
C#
1578
Chapter 213. Maximum and Minimum Values of an Algebraic Expression
{
sum += arr[i];
// shifting the integers by 50
// so that they become positive
arr[i] += 50;
}
// dp[i][j] represents true if sum
// j can be reachable by choosing
// i numbers
bool[,] dp = new bool[MAX+1, MAX * MAX + 1];
dp[0,0] = true;
// if dp[i][j] is true, that means
// it is possible to select i numbers
// from (n + m) numbers to sum upto j
for (int i = 0; i < (n + m); i++) {
// k can be at max n because the
// left expression has n numbers
for (int k = Math.Min(n, i + 1); k >= 1; k--)
{
for (int j = 0; j < MAX * MAX + 1; j++)
{
if (dp[k - 1,j])
dp[k,j + arr[i]] = true;
}
}
}
double max_value = -1 * INF, min_value = INF;
for (int i = 0; i < MAX * MAX + 1; i++)
{
// checking if a particular sum
// can be reachable by choosing
// n numbers
if (dp[n,i]) {
// getting the actual sum as
// we shifted the numbers by
/// 50 to avoid negative indexing
// in array
int temp = i - 50 * n;
max_value = Math.Max(max_value, temp *
1579
Chapter 213. Maximum and Minimum Values of an Algebraic Expression
(sum - temp));
min_value = Math.Min(min_value, temp *
(sum - temp));
}
}
Console.WriteLine("Maximum Value: " + max_value
+ "\n" + "Minimum Value: " + min_value + "\n");
}
// Driver Code
public static void Main()
{
int n = 2, m = 2;
int []arr = { 1, 2, 3, 4 };
minMaxValues(arr, n, m);
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
PHP
<?php
// PHP program to find the
// maximum and minimum values
// of an Algebraic expression
// of given form
function minMaxValues($arr, $n, $m)
{
// Finding sum of
// array elements
$sum = 0;
$INF = 1000000000;
$MAX = 50;
for ($i = 0; $i < ($n + $m); $i++)
{
$sum += $arr[$i];
// shifting the integers by 50
// so that they become positive
$arr[$i] += 50;
}
// dp[i][j] represents true
// if sum j can be reachable
1580
Chapter 213. Maximum and Minimum Values of an Algebraic Expression
1581
Chapter 213. Maximum and Minimum Values of an Algebraic Expression
Output :
Maximum Value: 25
Minimum Value: 21
Source
https://www.geeksforgeeks.org/maximum-minimum-values-algebraic-expression/
1582
Chapter 214
Input : A = { 9, 1, 2, 3, 9 }
K=3
Output : 20
Explanation : We can partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 +
2 + 3) / 3 + 9 = 20.
We could have also partitioned A into [9, 1], [2], [3, 9]. That partition would
lead to a score of 5 + 2 + 6 = 13, which is worse.
Input : A[] = { 1, 2, 3, 4, 5, 6, 7 }
K=4
Output : 20.5
Explanation : We can partition A into [1, 2, 3, 4], [5], [6], [7]. The answer is 2.5
+ 5 + 6 + 7 = 20.5.
1583
Chapter 214. Maximum average sum partition of an array
Output:
20
1584
Chapter 214. Maximum average sum partition of an array
Output:
20
1585
Chapter 214. Maximum average sum partition of an array
Source
https://www.geeksforgeeks.org/maximum-average-sum-partition-array/
1586
Chapter 215
// If i or j is our of boundary
If i >= n || j >= n
return 0
1587
Chapter 215. Maximum decimal value path in a binary matrix
If mat[i][j] == 1
return power(2, p) + result
Else
return result
// C++ program to find maximum decimal value path in
// binary matrix
#include<bits/stdc++.h>
using namespace std;
#define N 4
// Returns maximum decimal value in binary matrix.
// Here p indicate power of 2
long long int maxDecimalValue(int mat[][N], int i, int j,
int p)
{
// Out of matrix boundary
if (i >= N || j >= N )
return 0;
int result = max(maxDecimalValue(mat, i, j+1, p+1),
maxDecimalValue(mat, i+1, j, p+1));
// If current matrix value is 1 then return result +
// power(2, p) else result
if (mat[i][j] == 1)
return pow(2, p) + result;
else
return result;
}
//Driver program
int main()
{
int mat[][4] = {{ 1 ,1 ,0 ,1 },
{ 0 ,1 ,1 ,0 },
{ 1 ,0 ,0 ,1 },
1588
Chapter 215. Maximum decimal value path in a binary matrix
{ 1 ,0 ,1 ,1 },
};
cout << maxDecimalValue(mat, 0, 0, 0) << endl;
return 0;
}
Python3
PHP
<?php
1589
Chapter 215. Maximum decimal value path in a binary matrix
Output:
111
1590
Chapter 215. Maximum decimal value path in a binary matrix
If we see recursion tree of above recursive solution, we can observe overlapping sub-problems.
Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic
Programming. Below is Dynamic Programming based solution.
Below is c++ implementation of above problem using Dynamic Programming
1591
Chapter 215. Maximum decimal value path in a binary matrix
{
// indicate 1*(2^i) + result of previous
if (mat[i][0] == 1)
dp[i][0] = dp[i-1][0] + pow(2, i);
// indicate 0*(2^i) + result of previous
else
dp[i][0] = dp[i-1][0];
}
// Traversal rest Binary matrix and Compute maximum
// decimal value
for (int i=1 ; i < n ; i++ )
{
for (int j=1 ; j < n ; j++ )
{
// Here (i+j) indicate the current power of
// 2 in path that is 2^(i+j)
if (mat[i][j] == 1)
dp[i][j] = max(dp[i][j-1], dp[i-1][j]) +
pow(2, i+j);
else
dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
}
}
// Return maximum decimal value in binary matrix
return dp[n-1][n-1];
}
// Driver program
int main()
{
int mat[][4] = {{ 1 ,1 ,0 ,1 },
{ 0 ,1 ,1 ,0 },
{ 1 ,0 ,0 ,1 },
{ 1 ,0 ,1 ,1 },
};
cout << MaximumDecimalValue(mat, 4) << endl;
return 0;
}
Output:
111
1592
Chapter 215. Maximum decimal value path in a binary matrix
Source
https://www.geeksforgeeks.org/maximum-decimal-value-path-in-a-binary-matrix/
1593
Chapter 216
Input : S = "11000010001"
Output : 6
From index 2 to index 9, there are 7
0s and 1 1s, so number of 0s - number
of 1s is 6.
Input : S = "1111"
Output : -1
1594
Chapter 216. Maximum difference of zeros and ones in binary string
1595
Chapter 216. Maximum difference of zeros and ones in binary string
else
return dp[ind][st] = max(arr[ind] +
findlength(arr, s, n, ind + 1, 1, dp), 0);
}
// Returns length of substring which is
// having maximum difference of number
// of 0s and number of 1s
int maxLen(string s, int n)
{
// If all 1s return -1.
if (allones(s, n))
return -1;
// Else find the length.
int arr[MAX] = { 0 };
for (int i = 0; i < n; i++)
arr[i] = (s[i] == '0' ? 1 : -1);
int dp[MAX][3];
memset(dp, -1, sizeof dp);
return findlength(arr, s, n, 0, 0, dp);
}
// Driven Program
int main()
{
string s = "11000010001";
int n = 11;
cout << maxLen(s, n) << endl;
return 0;
}
Java
1596
Chapter 216. Maximum difference of zeros and ones in binary string
1597
Chapter 216. Maximum difference of zeros and ones in binary string
Python3
1598
Chapter 216. Maximum difference of zeros and ones in binary string
Output :
Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
Source
https://www.geeksforgeeks.org/maximum-difference-zeros-ones-binary-string/
1599
Chapter 217
Maximum difference of zeros and ones in binary string | Set 2 (O(n) time) - GeeksforGeeks
Given a binary string of 0s and 1s. The task is to find the length of substring which is
having a maximum difference of number of 0s and number of 1s (number of 0s – number of
1s). In case of all 1s print -1.
Examples:
Input : S = "11000010001"
Output : 6
From index 2 to index 9, there are 7
0s and 1 1s, so number of 0s - number
of 1s is 6.
Input : S = "1111"
Output : -1
Input : S = "11000010001"
1600
Chapter 217. Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
Output : 6
C++
1601
Chapter 217. Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
// Driven Program
int main()
{
string s = "11000010001";
int n = 11;
cout << findLength(s, n) << endl;
return 0;
}
Java
1602
Chapter 217. Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
public static void main(String[] args)
{
String str = "11000010001";
int n = str.length();
System.out.println(findLength(str, n));
}
}
Python3
1603
Chapter 217. Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
PHP
<?php
// PHP Program to find the length of
// substring with maximum difference of
// zeros and ones in binary string.
// Returns the length of substring with
// maximum difference of zeroes and ones
// in binary string
function findLength($str, $n)
{
$current_sum = 0;
$max_sum = 0;
// traverse a binary string
// from left to right
for ($i = 0; $i < $n; $i++)
{
// add current value to the current_sum
// according to the Character
// if it's '0' add 1 else -1
$current_sum += ($str[$i] == '0' ? 1 : -1);
if ($current_sum < 0)
$current_sum = 0;
// update maximum sum
$max_sum = max($current_sum, $max_sum);
}
// return -1 if string does not contain
// any zero that means all ones
// otherwise max_sum
return $max_sum == 0 ? -1 : $max_sum;
}
// Driver Code
$s = "11000010001";
$n = 11;
echo findLength($s, $n),"\n";
// This code is contributed by aj_36
?>
1604
Chapter 217. Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
Output:
Source
https://www.geeksforgeeks.org/maximum-difference-zeros-ones-binary-string-set-2-time/
1605
Chapter 218
Input : N = 3
Output : 2
Maximum games winner can play = 2
Assume that player are P1, P2 and P3
First, two players will play let (P1, P2)
Now winner will play against P3,
making total games played by winner = 2
Input : N = 4
Output : 2
Maximum games winner can play = 2
Assume that player are P1, P2, P3 and P4
First two pairs will play lets (P1, P2) and
(P3, P4). Now winner of these two games will
play against each other, making total games
played by winner = 2
We can solve this problem by first computing minimum number of players required such
that the winner will play x games. Once this is computed actual problem is just inverse of
this. Now assume that dp[i] denotes minimum number of players required so that winner
plays i games. We can write a recursive relation among dp values as,
1606
Chapter 218. Maximum games played by winner
dp[i + 1] = dp[i] + dp[i – 1] because if runner up has played (i – 1) games and winner has
played i games and all players against which they have played the match are disjoint, total
games played by winner will be addition of those two sets of players.
Above recursive relation can be written as dp[i] = dp[i – 1] + dp[i – 2]
Which is same as the Fibonacci series relation, so our final answer will be the index of the
maximal Fibonacci number which is less than or equal to given number of players in the
input.
C++
Java
1607
Chapter 218. Maximum games played by winner
Output:
C#
1608
Chapter 218. Maximum games played by winner
using System;
class GFG {
// method returns maximum games a
// winner needs to play in N-player
// tournament
static int maxGameByWinner(int N)
{
int[] dp = new int[N];
// for 0 games, 1 player is needed
// for 1 game, 2 players are required
dp[0] = 1;
dp[1] = 2;
// loop until i-th Fibonacci number
// is less than or equal to N
int i = 2;
do {
dp[i] = dp[i - 1] + dp[i - 2];
} while (dp[i++] <= N);
// result is (i - 2) because i will be
// incremented one extra in while loop
// and we want the last value which is
// smaller than N, so one more decrement
return (i - 2);
}
// Driver code
public static void Main()
{
int N = 10;
Console.Write(maxGameByWinner(N));
}
}
// This code is contributed by Nitin Mittal.
PHP
<?php
// PHP program to find maximum number
// of games played by winner
// Method returns maximum games
1609
Chapter 218. Maximum games played by winner
Output :
Source
https://www.geeksforgeeks.org/maximum-games-played-winner/
1610
Chapter 219
Approach:
1611
Chapter 219. Maximum length of segments of 0’s and 1’s
5. Else only recursively call the function for next index k+1.
6. Return dp[start].
1612
Chapter 219. Maximum length of segments of 0’s and 1’s
// Driver Code
int main()
{
string adj = "100110001010001";
// Size of string
int n = adj.size();
int dp[n + 1];
memset(dp, -1, sizeof(dp));
// Calling the function to find the value of function
cout << find(0, adj, n, dp) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/maximum-length-of-segments-of-0s-and-1s/
1613
Chapter 220
1614
Chapter 220. Maximum length subsequence with difference between adjacent elements as
either 0 or 1
Java
1615
Chapter 220. Maximum length subsequence with difference between adjacent elements as
either 0 or 1
import java.util.*;
class GFG {
// function to find maximum length subsequence
// with difference between adjacent elements as
// either 0 or 1
public static int maxLenSub(int arr[], int n)
{
int mls[] = new int[n], max = 0;
// Initialize mls[] values for all indexes
for (int i = 0; i < n; i++)
mls[i] = 1;
// Compute optimized maximum length
// subsequence values in bottom up manner
for (int i = 1; i < n; i++)
for (int j = 0; j < i; j++)
if (Math.abs(arr[i] - arr[j]) <= 1
&& mls[i] < mls[j] + 1)
mls[i] = mls[j] + 1;
// Store maximum of all 'mls' values in 'max'
for (int i = 0; i < n; i++)
if (max < mls[i])
max = mls[i];
// required maximum length subsequence
return max;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = {2, 5, 6, 3, 7, 6, 5, 8};
int n = arr.length;
System.out.println("Maximum length subsequence = "+
maxLenSub(arr, n));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
1616
Chapter 220. Maximum length subsequence with difference between adjacent elements as
either 0 or 1
C#
1617
Chapter 220. Maximum length subsequence with difference between adjacent elements as
either 0 or 1
PHP
<?php
// PHP implementation to find maximum length
// subsequence with difference between adjacent
// elements as either 0 or 1
// function to find maximum length subsequence
// with difference between adjacent elements as
// either 0 or 1
1618
Chapter 220. Maximum length subsequence with difference between adjacent elements as
either 0 or 1
Output:
1619
Chapter 220. Maximum length subsequence with difference between adjacent elements as
either 0 or 1
Source
https://www.geeksforgeeks.org/maximum-length-subsequence-difference-adjacent-elements-either-0-1/
1620
Chapter 221
Input : N = 7, a = 5, b, = 2, c = 5
Output : 2
N can be divided into 2 segments of lengths
2 and 5. For the second example,
Input : N = 17, a = 2, b = 1, c = 3
Output : 17
N can be divided into 17 segments of 1 or 8
segments of 2 and 1 segment of 1. But 17 segments
of 1 is greater than 9 segments of 2 and 1.
Approach : The approach used is Dynamic Programming. The base dp0 will be 0 as
initially it has no segments. After that, iterate from 1 to n, and for each of the 3 states i.e,
dpi+a , dpi+b and dpi+c , store the maximum value obtained by either using or not using the
a, b or c segment.
The 3 states to deal with are :
1621
Chapter 221. Maximum number of segments of lengths a, b and c
C++
1622
Chapter 221. Maximum number of segments of lengths a, b and c
Java
1623
Chapter 221. Maximum number of segments of lengths a, b and c
// Driver code
public static void main(String arg[])
{
int n = 7, a = 5, b = 2, c = 5;
System.out.print(maximumSegments(n, a, b, c));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python implementation
# to divide N into maximum
# number of segments of
# length a, b and c
# function to find
# the maximum number
# of segments
def maximumSegments(n, a, b, c) :
# stores the maximum
# number of segments
# each index can have
dp = [-1] * (n + 10)
# 0th index will have
# 0 segments base case
dp[0] = 0
# traverse for all possible
# segments till n
for i in range(0, n) :
if (dp[i] != -1) :
# conditions
dp[i + a] = max(dp[i] + 1,
dp[i + a])
dp[i + b] = max(dp[i] + 1,
dp[i + b])
dp[i + c] = max(dp[i] + 1,
dp[i + c])
return dp[n]
1624
Chapter 221. Maximum number of segments of lengths a, b and c
# Driver code
n = 7
a = 5
b = 2
c = 5
print (maximumSegments(n, a,
b, c))
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
1625
Chapter 221. Maximum number of segments of lengths a, b and c
dp[i + a]);
dp[i + b] = Math.Max(dp[i] + 1,
dp[i + b]);
dp[i + c] = Math.Max(dp[i] + 1,
dp[i + c]);
}
}
return dp[n];
}
// Driver code
public static void Main()
{
int n = 7, a = 5, b = 2, c = 5;
Console.Write(maximumSegments(n, a, b, c));
}
}
// This code is contributed by nitin mittal
PHP
<?php
// PHP implementation to divide
// N into maximum number of
// segments of length a, b and c
// function to find the maximum
// number of segments
function maximumSegments($n, $a,
$b, $c)
{
// stores the maximum
// number of segments
// each index can have
$dp = array();
// initialize with -1
for($i = 0; $i < $n + 10; $i++)
$dp[$i]= -1;
// 0th index will have
// 0 segments base case
$dp[0] = 0;
// traverse for all possible
// segments till n
1626
Chapter 221. Maximum number of segments of lengths a, b and c
Output :
Source
https://www.geeksforgeeks.org/maximum-number-segments-lengths-b-c/
1627
Chapter 222
Maximum number of trailing zeros in the product of the subsets of size k - GeeksforGeeks
Given an array of size n and a positive integer k, find the maximum number of trailing zeros
in the product of the subsets of size k.
Examples:
1628
Chapter 222. Maximum number of trailing zeros in the product of the subsets of size k
1629
Chapter 222. Maximum number of trailing zeros in the product of the subsets of size k
// arr[p].
while (arr[p] % 5 == 0) {
pw5++;
arr[p] /= 5;
}
// Calculating subset[i][j] for maximum
// amount of twos we can collect by
// checking first i numbers and taking
// j of them with total power of five.
for (int i = k - 1; i >= 0; i--)
for (int j = 0; j < MAX5; j++)
// If subset[i][j] is not calculated.
if (subset[i][j] != -1)
subset[i + 1][j + pw5] =
max(subset[i + 1][j + pw5],
subset[i][j] + pw2);
}
// Calculating maximal number of zeros.
// by taking minimum of 5 or 2 and then
// taking maximum.
int ans = 0;
for (int i = 0; i < MAX5; i++)
ans = max(ans, min(i, subset[k][i]));
return ans;
}
// Driver function
int main()
{
int arr[] = { 50, 4, 20 };
int k = 2;
int n = sizeof(arr) / sizeof(arr[0]);
cout << maximumZeros(arr, n, k) << endl;
return 0;
}
Python3
1630
Chapter 222. Maximum number of trailing zeros in the product of the subsets of size k
1631
Chapter 222. Maximum number of trailing zeros in the product of the subsets of size k
# Driver function
arr = [ 50, 4, 20 ]
k = 2
n = len(arr)
print(maximumZeros(arr, n, k))
# This code is contributed by Ansu Kumari.
Output :
Source
https://www.geeksforgeeks.org/maximum-number-of-trailing-zeros-in-the-product-of-the-subsets-of-size-k/
1632
Chapter 223
Maximum path sum for each position with jumps under divisibility condition - Geeks-
forGeeks
Given an array of n positive integers. Initially we are at first position. We can jump to
position y (1 <= x <= n) from position x (1 <= x <= n) if x divides y and x < y. The task
is to print maximum sum path ending at every position x. Note : Since first element is at
position 1, we can jump to any position from here as 1 divides all other position numbers.
Examples :
1633
Chapter 223. Maximum path sum for each position with jumps under divisibility condition
C++
1634
Chapter 223. Maximum path sum for each position with jumps under divisibility condition
Java
1635
Chapter 223. Maximum path sum for each position with jumps under divisibility condition
1636
Chapter 223. Maximum path sum for each position with jumps under divisibility condition
Python3
1637
Chapter 223. Maximum path sum for each position with jumps under divisibility condition
C#
1638
Chapter 223. Maximum path sum for each position with jumps under divisibility condition
Output:
2 5 3 9 8 10
Source
https://www.geeksforgeeks.org/maximum-path-sum-position-jumps-divisibility-condition/
1639
Chapter 224
Input :
3
7 4
2 4 6
8 5 9 3
Output : 23
Explanation : 3 + 7 + 4 + 9 = 23
Input :
8
-4 4
2 2 6
1 1 1 1
Output : 19
Explanation : 8 + 4 + 6 + 1 = 19
We can go through the brute force by checking every possible path but that is much time
taking so we should try to solve this problem with the help of dynamic programming which
reduces the time complexity.
If we should left shift every element and put 0 at each empty position to make it a regular
matrix, then our problem looks like minimum cost path.
So, after converting our input triangle elements into a regular matrix we should apply the
1640
Chapter 224. Maximum path sum in a triangle.
3
7 4
2 4 6
8 5 9 3
Step 1 :
3 0 0 0
7 4 0 0
2 4 6 0
8 5 9 3
Step 2 :
3 0 0 0
7 4 0 0
10 13 15 0
Step 3 :
3 0 0 0
20 19 0 0
Step 4:
23 0 0 0
output : 23
C++
1641
Chapter 224. Maximum path sum in a triangle.
Java
1642
Chapter 224. Maximum path sum in a triangle.
Python3
1643
Chapter 224. Maximum path sum in a triangle.
else:
tri[i][j] += tri[i+1][j+1]
# return the top element
# which stores the maximum sum
return tri[0][0]
# Driver program to test above function
tri = [[1, 0, 0],
[4, 8, 0],
[1, 5, 3]]
print(maxPathSum(tri, 2, 2))
# This code is contributed
# by Soumen Ghosh.
C#
1644
Chapter 224. Maximum path sum in a triangle.
}
}
// return the top element
// which stores the maximum sum
return tri[0,0];
}
/* Driver program to test above
functions */
public static void Main ()
{
int [,]tri = { {1, 0, 0},
{4, 8, 0},
{1, 5, 3} };
Console.Write (
maxPathSum(tri, 2, 2));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program for Dynamic
// Programming implementation of
// Max sum problem in a triangle
// Function for finding
// maximum sum
function maxPathSum($tri, $m, $n)
{
// loop for bottom-up
// calculation
for ( $i = $m - 1; $i >= 0; $i--)
{
for ($j = 0; $j <= $i; $j++)
{
// for each element, check
// both elements just below
// the number and below right
// to the number add the maximum
// of them to it
if ($tri[$i + 1][$j] > $tri[$i + 1]
[$j + 1])
$tri[$i][$j] += $tri[$i + 1][$j];
1645
Chapter 224. Maximum path sum in a triangle.
else
$tri[$i][$j] += $tri[$i + 1]
[$j + 1];
}
}
// return the top element
// which stores the maximum sum
return $tri[0][0];
}
// Driver Code
$tri= array(array(1, 0, 0),
array(4, 8, 0),
array(1, 5, 3));
echo maxPathSum($tri, 2, 2);
// This code is contributed by ajit
?>
Output :
14
Source
https://www.geeksforgeeks.org/maximum-path-sum-triangle/
1646
Chapter 225
Maximum path sum that starting with any cell of 0-th row and ending with any cell of
(N-1)-th row - GeeksforGeeks
Given a N X N matrix Mat[N][N] of positive integers. There are only three possible moves
from a cell (i, j)
1. (i+1, j)
2. (i+1, j-1)
3. (i+1, j+1)
Starting from any column in row 0, return the largest sum of any of the paths up to row
N-1.
Examples:
1647
Chapter 225. Maximum path sum that starting with any cell of 0-th row and ending with
any cell of (N-1)-th row
i = N-1, j = 0 to N -1
int MaximumPath(Mat[][N], I, j)
If we draw recursion tree of above recursive solution, we can observe overlapping subprob-
lems. Since the problem has overlapping subproblems, we can solve it efficiently using
Dynamic Programming. Below is Dynamic Programming based solution.
CPP
1648
Chapter 225. Maximum path sum that starting with any cell of 0-th row and ending with
any cell of (N-1)-th row
Java
1649
Chapter 225. Maximum path sum that starting with any cell of 0-th row and ending with
any cell of (N-1)-th row
class GFG {
static int N = 4;
// function find maximum sum path
static int MaximumPath(int Mat[][])
{
int result = 0;
// creat 2D matrix to store the sum
// of the path
int dp[][] = new int[N][N + 2];
// initialize all dp matrix as '0'
for (int[] rows : dp)
Arrays.fill(rows, 0);
// copy all element of first column into
// 'dp' first column
for (int i = 0; i < N; i++)
dp[0][i + 1] = Mat[0][i];
for (int i = 1; i < N; i++)
for (int j = 1; j <= N; j++)
dp[i][j] = Math.max(dp[i - 1][j - 1],
Math.max(dp[i - 1][j],
dp[i - 1][j + 1])) +
Mat[i][j - 1];
// Find maximum path sum that end ups
// at any column of last row 'N-1'
for (int i = 0; i <= N; i++)
result = Math.max(result, dp[N - 1][i]);
// return maximum sum path
return result;
}
// driver code
public static void main(String arg[])
{
int Mat[][] = { { 4, 2, 3, 4 },
{ 2, 9, 1, 10 },
{ 15, 1, 3, 0 },
{ 16, 92, 41, 44 } };
System.out.println(MaximumPath(Mat));
}
1650
Chapter 225. Maximum path sum that starting with any cell of 0-th row and ending with
any cell of (N-1)-th row
}
// This code is contributed by Anant Agarwal.
Python3
1651
Chapter 225. Maximum path sum that starting with any cell of 0-th row and ending with
any cell of (N-1)-th row
# This code is contributed by Soumen Ghosh.
Output:
120
Source
https://www.geeksforgeeks.org/maximum-path-sum-starting-cell-0-th-row-ending-cell-n-1-th-row/
1652
Chapter 226
1653
Chapter 226. Maximum points collected by two persons allowed to meet once
P1 needs to move from top left (0, 0) to bottom right (n-1, m-1). P1 can move right and
down, i.e., from A[i][j] to A[i][j+1] or A[i+1][j]
P2 needs to move from bottom left (n-1, 0) to top right (0, m-1). P2 can move right and
up, i.e., from A[i][j] to A[i][j+1] or A[i-1][j].
The idea is to consider every point as a meeting point and find maximum of all meeting
points. When we consider a point A[i][j] as meeting point, we need to have following four
values to find maximum total points collected when A[i][j] is meeting point.
1) Points collected by P1 from (0, 0) to (i, j).
2) Points collected by P1 from (i, j) to (n-1, m-1).
3) Points collected by P2 from (n-1, 0) to (i, j).
4) Points collected by P2 from (i, j) to (0, m-1).
We can compute above four values using Dynamic Programming. Once we have above four
values for every point, we can find maximum points at every meeting point.
For every meeting points, there are two possible values to reach it and leave it as we are
allowed to have only one meeting point.
1) P1 reaches it through a right move and p2 through a up move and they leave same way
also.
2) P1 reaches it through a down move and p2 through a right move and they leave same
way also.
We take maximum of above two values to find optimal points at this meeting point.
Finally, we return maximum of all meeting points.
1654
Chapter 226. Maximum points collected by two persons allowed to meet once
1655
Chapter 226. Maximum points collected by two persons allowed to meet once
// Driver code
int main()
{
//input the calories burnt matrix
int A[][M] = {{100, 100, 100},
{100, 1, 100},
{100, 100, 100}};
cout << "Max Points : " << findMaxPoints(A);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/maximum-points-collected-by-two-persons-allowed-to-meet-once/
1656
Chapter 227
Maximum points from top left of matrix to bottom right and return back - GeeksforGeeks
Given a matrix of size N X M consisting of ‘#’, ‘.’ and ‘*’. ‘#’ means blocked path, ‘.’
means walkable path and ‘*’ means point you have to collect. Now consider you are at top
left of the matrix. You have to reach bottom right of the matrix and come back to top left.
When you are moving top left to bottom right, you are allowed to walk right or down. And
when you are moving bottom right to top left, you are allowed to walk left or up. The task
is find the maximum points you can grab during your whole journey. Points once taken will
be converted into ‘.’ i.e walkable path.
Examples:
Input : N = 3, M = 4
****
.##.
.##.
****
Output : 8
Input : N = 9, M = 7
*........
.....**#.
..**...#*
..####*#.
.*.#*.*#.
...#**...
*........
1657
Chapter 227. Maximum points from top left of matrix to bottom right and return back
Output : 7
If you consider two paths – one from (0, 0) to (N – 1, M – 1) and another from (N – 1, M –
1) to (0, 0) and collect maximum * in each path. You might end up with wrong answer. If
you add the answer of both the paths independently, you will be calculating the intersecting
points once again while backtracking. Essentially, ending up with the same path. Even if
you keep a visited array, marking every * on the first path, you will still not end up with
the correct answer.
Consider the following example:
total * collected is 7.
Whereas the maximum points collected can be 8 by following paths.
1658
Chapter 227. Maximum points from top left of matrix to bottom right and return back
1659
Chapter 227. Maximum points from top left of matrix to bottom right and return back
#define M 5
#define inf 100000
using namespace std;
// Calculating the points at a (row1, col1) &&
// (row2, col2) from path1 && path2
int cost(char grid[][M], int row1, int col1,
int row2, int col2)
{
// If both path is at same cell
if (row1 == row2 && col1 == col2) {
// If the cell contain *, return 1
if (grid[row1][col1] == '*')
return 1;
// else return 0.
return 0;
}
int ans = 0;
// If path 1 contain *, add to answer.
if (grid[row1][col1] == '*')
ans++;
// If path contain *, add to answer.
if (grid[row2][col2] == '*')
ans++;
return ans;
}
// Calculate the maximum points that can be
// collected.
int solve(int n, int m, char grid[][M],
int dp[MAX][MAX][MAX], int row1,
int col1, int row2)
{
int col2 = (row1 + col1) - (row2);
// If both path reach the bottom right cell
if (row1 == n - 1 && col1 == m - 1 &&
row2 == n - 1 && col2 == m - 1)
return 0;
// If moving out of grid
if (row1 >= n || col1 >= m ||
1660
Chapter 227. Maximum points from top left of matrix to bottom right and return back
1661
Chapter 227. Maximum points from top left of matrix to bottom right and return back
Output:
Source
https://www.geeksforgeeks.org/maximum-points-top-left-matrix-bottom-right-return-back/
1662
Chapter 228
Maximum product of an
increasing subsequence
C++
1663
Chapter 228. Maximum product of an increasing subsequence
Java
1664
Chapter 228. Maximum product of an increasing subsequence
Python3
1665
Chapter 228. Maximum product of an increasing subsequence
# Returns product of maximum product
# increasing subsequence.
def lis (arr, n ):
mpis =[0] * (n)
# Initialize MPIS values
for i in range(n):
mpis[i] = arr[i]
# Compute optimized MPIS values
# considering every element as
# ending element of sequence
for i in range(1, n):
for j in range(i):
if (arr[i] > arr[j] and
mpis[i] < (mpis[j] * arr[i])):
mpis[i] = mpis[j] * arr[i]
# Pick maximum of all product values
return max(mpis)
# Driver code to test above function
arr = [3, 100, 4, 5, 150, 6]
n = len(arr)
print( lis(arr, n))
# This code is contributed by "Sharad_Bhardwaj".
C#
1666
Chapter 228. Maximum product of an increasing subsequence
/* Compute optimized MPIS values considering
every element as ending element of sequence */
for (int i = 1; i < n; i++)
for (int j = 0; j < i; j++)
if (arr[i] > arr[j] && mpis[i] < (mpis[j] * arr[i]))
mpis[i] = mpis[j] * arr[i];
/* Pick maximum of all product values */
return mpis.Max();
}
/* Driver program to test above function */
static public void Main()
{
long[] arr = { 3, 100, 4, 5, 150, 6 };
long n = arr.Length;
Console.WriteLine(lis(arr, n));
}
}
// This code is contributed by vt_m.
Output:
45000
Source
https://www.geeksforgeeks.org/maximum-product-increasing-subsequence/
1667
Chapter 229
Input:
Price = [10, 22, 5, 75, 65, 80]
K = 2
Output: 87
Trader earns 87 as sum of 12 and 75
Buy at price 10, sell at 22, buy at
5 and sell at 80
Input:
Price = [12, 14, 17, 10, 14, 13, 12, 15]
K = 3
Output: 12
Trader earns 12 as sum of 5, 4 and 3
Buy at price 12, sell at 17, buy at 10
and sell at 14 and buy at 12 and sell
at 15
Input:
Price = [100, 30, 15, 10, 8, 25, 80]
K = 3
Output: 72
Only one transaction. Buy at price 8
1668
Chapter 229. Maximum profit by buying and selling a share at most k times
Input:
Price = [90, 80, 70, 60, 50]
K = 1
Output: 0
Not possible to earn.
There are various versions of the problem. If we are allowed to buy and sell only once, then
we can use Maximum difference between two elements algorithm. If we are allowed to make
at most 2 transactions, we can follow approach discussed here. If we are allowed to buy and
sell any number of times, we can follow approach discussed here.
In this post, we are only allowed to make at max k transactions. The problem can be solve
by using dynamic programming.
Let profit[t][i] represent maximum profit using at most t transactions up to day i (including
day i). Then the relation is:
profit[t][i] = max(profit[t][i-1], max(price[i] – price[j] + profit[t-1][j]))
for all j in range [0, i-1]
profit[t][i] will be maximum of –
1. profit[t][i-1] which represents not doing any transaction on the ith day.
2. Maximum profit gained by selling on ith day. In order to sell shares on ith day, we
need to purchase it on any one of [0, i – 1] days. If we buy shares on jth day and sell
it on ith day, max profit will be price[i] – price[j] + profit[t-1][j] where j varies from 0
to i-1. Here profit[t-1][j] is best we could have done with one less transaction till jth
day.
C++
1669
Chapter 229. Maximum profit by buying and selling a share at most k times
Java
1670
Chapter 229. Maximum profit by buying and selling a share at most k times
1671
Chapter 229. Maximum profit by buying and selling a share at most k times
}
}
return profit[k][n - 1];
}
// Driver code
public static void main(String []args)
{
int k = 2;
int[] price = { 10, 22, 5, 75, 65, 80 };
int n = price.length;
System.out.println("Maximum profit is: " +
maxProfit(price, n, k));
}
}
// This code is contributed by Anshul Aggarwal.
Python3
1672
Chapter 229. Maximum profit by buying and selling a share at most k times
# Driver code
k = 2
prices = [10, 22, 5, 75, 65, 80]
n = len(prices)
print("Maximum profit is:",
maxProfit(prices, n, k))
# This code is contributed by vaibhav29498
C#
1673
Chapter 229. Maximum profit by buying and selling a share at most k times
profit[i, j] = Math.Max(profit[i, j - 1], max_so_far);
}
}
return profit[k, n - 1];
}
// Driver code to test above
public static void Main()
{
int k = 2;
int[] price = { 10, 22, 5, 75, 65, 80 };
int n = price.Length;
Console.Write("Maximum profit is: " +
maxProfit(price, n, k));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to find out maximum profit by
// buying and selling a share atmost k times
// given stock price of n days
// Function to find out maximum profit by buying
// & selling a share atmost k times given stock
// price of n days
function maxProfit($price, $n, $k)
{
// table to store results of subproblems
// profit[t][i] stores maximum profit using
// atmost t transactions up to day i (including
// day i)
$profit[$k + 1][$n + 1] = 0;
// For day 0, you can't earn money
// irrespective of how many times you trade
for ($i = 0; $i <= $k; $i++)
$profit[$i][0] = 0;
// profit is 0 if we don't
1674
Chapter 229. Maximum profit by buying and selling a share at most k times
Output :
Optimized Solution:
The above solution has time complexity of O(k.n2 ). It can be reduced if we are able to
calculate maximum profit gained by selling shares on ith day in constant time.
profit[t][i] = max(profit [t][i-1], max(price[i] – price[j] + profit[t-1][j]))
for all j in range [0, i-1]
If we carefully notice,
max(price[i] – price[j] + profit[t-1][j])
for all j in range [0, i-1]
can be rewritten as,
= price[i] + max(profit[t-1][j] – price[j])
1675
Chapter 229. Maximum profit by buying and selling a share at most k times
C++
1676
Chapter 229. Maximum profit by buying and selling a share at most k times
Java
1677
Chapter 229. Maximum profit by buying and selling a share at most k times
C#
1678
Chapter 229. Maximum profit by buying and selling a share at most k times
// Function to find out maximum profit by
// buying & selling/ a share atmost k times
// given stock price of n days
static int maxProfit(int[] price, int n, int k)
{
// table to store results of subproblems
// profit[t][i] stores maximum profit using atmost
// t transactions up to day i (including day i)
int[, ] profit = new int[k + 1, n + 1];
// For day 0, you can't earn money
// irrespective of how many times you trade
for (int i = 0; i <= k; i++)
profit[i, 0] = 0;
// profit is 0 if we don't do any transation
// (i.e. k =0)
for (int j = 0; j <= n; j++)
profit[0, j] = 0;
// fill the table in bottom-up fashion
for (int i = 1; i <= k; i++) {
int prevDiff = int.MinValue;
for (int j = 1; j < n; j++) {
prevDiff = Math.Max(prevDiff,
profit[i - 1, j - 1] - price[j - 1]);
profit[i, j] = Math.Max(profit[i, j - 1],
price[j] + prevDiff);
}
}
return profit[k, n - 1];
}
// Driver code to test above
public static void Main()
{
int k = 3;
int[] price = {12, 14, 17, 10, 14, 13, 12, 15};
int n = price.Length;
Console.Write("Maximum profit is: " +
maxProfit(price, n, k));
}
}
1679
Chapter 229. Maximum profit by buying and selling a share at most k times
PHP
<?php
// PHP program to find out maximum
// profit by buying and selling a
// share atmost k times given stock
// price of n days
// Function to find out maximum
// profit by buying & selling a
// share atmost k times given
// stock price of n days
function maxProfit($price, $n, $k)
{
// table to store results
// of subproblems profit[t][i]
// stores maximum profit using
// atmost t transactions up to
// day i (including day i)
$profit[$k + 1][$n + 1]=0;
// For day 0, you can't
// earn money irrespective
// of how many times you trade
for ($i = 0; $i <= $k; $i++)
$profit[$i][0] = 0;
// profit is 0 if we don't
// do any transation
// (i.e. k =0)
for ($j = 0; $j <= $n; $j++)
$profit[0][$j] = 0;
// fill the table in
// bottom-up fashion
$prevDiff = NULL;
for ($i = 1; $i <= $k; $i++) {
for ($j = 1; $j < $n; $j++) {
$prevDiff = max($prevDiff, $profit[$i - 1][$j - 1] -
$price[$j - 1]);
$profit[$i][$j] = max($profit[$i][$j - 1],
$price[$j] + $prevDiff);
}
}
return $profit[$k][$n - 1];
1680
Chapter 229. Maximum profit by buying and selling a share at most k times
}
// Driver Code
$k = 3;
$price = array(12, 14, 17, 10,
14, 13, 12, 15);
$n = sizeof($price);
echo "Maximum profit is: "
, maxProfit($price, $n, $k);
// This code is contributed by nitin mittal
?>
Output :
Time complexity of above solution is O(kn) and space complexity is O(nk). Space complexity
can further be reduced to O(n) as we uses the result from last transaction. But to make the
article easily readable, we have used O(kn) space.
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Sam007, Anshul_Aggarwal, nitin mittal, Mithun Kumar, vaibhav29498
Source
https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-k-times/
1681
Chapter 230
1682
Chapter 230. Maximum profit by buying and selling a share at most twice
Maximum possible using one transaction can be calculated using following O(n) algorithm
Maximum difference between two elements such that larger element appears after the smaller
number
Time complexity of above simple solution is O(n2 ).
We can do this O(n) using following Efficient Solution. The idea is to store maximum
possible profit of every subarray and solve the problem in following two phases.
1) Create a table profit[0..n-1] and initialize all values in it 0.
2) Traverse price[] from right to left and update profit[i] such that profit[i] stores maximum
profit achievable from one transaction in subarray price[i..n-1]
3) Traverse price[] from left to right and update profit[i] such that profit[i] stores maxi-
mum profit such that profit[i] contains maximum achievable profit from two transactions in
subarray price[0..i].
4) Return profit[n-1]
To do step 1, we need to keep track of maximum price from right to left side and to do step
2, we need to keep track of minimum price from left to right. Why we traverse in reverse
directions? The idea is to save space, in second step, we use same array for both purposes,
maximum with 1 transaction and maximum with 2 transactions. After an iteration i, the
array profit[0..i] contains maximum profit with 2 transactions and profit[i+1..n-1] contains
profit with two transactions.
Below are implementations of above idea.
C++
1683
Chapter 230. Maximum profit by buying and selling a share at most twice
1684
Chapter 230. Maximum profit by buying and selling a share at most twice
Java
class Profit
{
// Returns maximum profit with two transactions on a given
// list of stock prices, price[0..n-1]
static int maxProfit(int price[], int n)
{
// Create profit array and initialize it as 0
int profit[] = new int[n];
for (int i=0; i<n; i++)
profit[i] = 0;
/* Get the maximum profit with only one transaction
allowed. After this loop, profit[i] contains maximum
profit from price[i..n-1] using at most one trans. */
int max_price = price[n-1];
for (int i=n-2;i>=0;i--)
{
// max_price has maximum of price[i..n-1]
if (price[i] > max_price)
max_price = price[i];
// we can get profit[i] by taking maximum of:
// a) previous maximum, i.e., profit[i+1]
// b) profit by buying at price[i] and selling at
// max_price
profit[i] = Math.max(profit[i+1], max_price-price[i]);
}
/* Get the maximum profit with two transactions allowed
After this loop, profit[n-1] contains the result */
int min_price = price[0];
for (int i=1; i<n; i++)
{
// min_price is minimum price in price[0..i]
if (price[i] < min_price)
min_price = price[i];
// Maximum profit is maximum of:
// a) previous maximum, i.e., profit[i-1]
// b) (Buy, Sell) at (min_price, price[i]) and add
// profit of other trans. stored in profit[i]
profit[i] = Math.max(profit[i-1], profit[i] +
(price[i]-min_price) );
}
int result = profit[n-1];
return result;
1685
Chapter 230. Maximum profit by buying and selling a share at most twice
}
public static void main(String args[])
{
int price[] = {2, 30, 15, 10, 8, 25, 80};
int n = price.length;
System.out.println("Maximum Profit = "+ maxProfit(price, n));
}
}/* This code is contributed by Rajat Mishra */
Python
1686
Chapter 230. Maximum profit by buying and selling a share at most twice
C#
1687
Chapter 230. Maximum profit by buying and selling a share at most twice
// we can get profit[i] by taking
// maximum of:
// a) previous maximum, i.e.,
// profit[i+1]
// b) profit by buying at price[i]
// and selling at max_price
profit[i] = Math.Max(profit[i+1],
max_price - price[i]);
}
/* Get the maximum profit with two
transactions allowed After this loop,
profit[n-1] contains the result */
int min_price = price[0];
for (int i = 1; i < n; i++)
{
// min_price is minimum price in
// price[0..i]
if (price[i] < min_price)
min_price = price[i];
// Maximum profit is maximum of:
// a) previous maximum, i.e.,
// profit[i-1]
// b) (Buy, Sell) at (min_price,
// price[i]) and add profit of
// other trans. stored in
// profit[i]
profit[i] = Math.Max(profit[i-1],
profit[i] + (price[i]
- min_price) );
}
int result = profit[n-1];
return result;
}
public static void Main()
{
int []price = {2, 30, 15, 10,
8, 25, 80};
int n = price.Length;
Console.Write("Maximum Profit = "
1688
Chapter 230. Maximum profit by buying and selling a share at most twice
PHP
<?php
// PHP program to find maximum
// possible profit with at most
// two transactions
// Returns maximum profit with
// two transactions on a given
// list of stock prices, price[0..n-1]
function maxProfit($price, $n)
{
// Create profit array and
// initialize it as 0
$profit = array();
for ($i = 0; $i < $n; $i++)
$profit[$i] = 0;
// Get the maximum profit with
// only one transaction allowed.
// After this loop, profit[i]
// contains maximum profit from
// price[i..n-1] using at most
// one trans.
$max_price = $price[$n - 1];
for ($i = $n - 2; $i >= 0; $i--)
{
// max_price has maximum
// of price[i..n-1]
if ($price[$i] > $max_price)
$max_price = $price[$i];
// we can get profit[i] by
// taking maximum of:
// a) previous maximum,
// i.e., profit[i+1]
// b) profit by buying at
// price[i] and selling at
// max_price
if($profit[$i + 1] >
$max_price-$price[$i])
$profit[$i] = $profit[$i + 1];
1689
Chapter 230. Maximum profit by buying and selling a share at most twice
else
$profit[$i] = $max_price -
$price[$i];
}
// Get the maximum profit with
// two transactions allowed.
// After this loop, profit[n-1]
// contains the result
$min_price = $price[0];
for ($i = 1; $i < $n; $i++)
{
// min_price is minimum
// price in price[0..i]
if ($price[$i] < $min_price)
$min_price = $price[$i];
// Maximum profit is maximum of:
// a) previous maximum,
// i.e., profit[i-1]
// b) (Buy, Sell) at (min_price,
// price[i]) and add
// profit of other trans.
// stored in profit[i]
$profit[$i] = max($profit[$i - 1],
$profit[$i] +
($price[$i] - $min_price));
}
$result = $profit[$n - 1];
return $result;
}
// Drive Code
$price = array(2, 30, 15, 10,
8, 25, 80);
$n = sizeof($price);
echo "Maximum Profit = ".
maxProfit($price, $n);
// This code is contributed
// by Arnab Kundu
?>
Output:
1690
Chapter 230. Maximum profit by buying and selling a share at most twice
Source
https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-twice/
1691
Chapter 231
C++
1692
Chapter 231. Maximum profit from sale of wines
1693
Chapter 231. Maximum profit from sale of wines
Java
1694
Chapter 231. Maximum profit from sale of wines
1695
Chapter 231. Maximum profit from sale of wines
dp[i][j] = -1;
int ans = maxProfitUtil(price, 0,
n - 1, n);
int i = 0, j = n - 1;
while (i <= j) {
// sell[i][j]=0 implies selling
// the wine from beginning will
// be more profitable in the
// long run
if(sell[i][j] == 0){
System.out.print( "beg ");
i++;
}
else
{
System.out.print( "end ");
j--;
}
}
System.out.println();
return ans;
}
// Driver code
public static void main (String[] args)
{
// Price array
int price[] = { 2, 4, 6, 2, 5 };
int n = price.length;
int ans = maxProfit(price, n);
System.out.println( ans );
}
}
// This code is contributed by anuj_67.
C#
1696
Chapter 231. Maximum profit from sale of wines
// price of wines
using System;
class GFG {
static int N = 1000;
static int [,]dp = new int[N, N];
// This array stores the "optimal action"
// for each state i, j
static int [,]sell = new int[N,N];
// Function to maximize profit
static int maxProfitUtil(int []price,
int begin, int end, int n)
{
if (dp[begin,end] != -1)
return dp[begin,end];
int year = n - (end - begin);
if (begin == end)
return year * price[begin];
// x = maximum profit on selling the
// wine from the front this year
int x = price[begin] * year +
maxProfitUtil(price, begin + 1,
end, n);
// y = maximum profit on selling the
// wine from the end this year
int y = price[end] * year +
maxProfitUtil(price, begin,
end - 1, n);
int ans = Math.Max(x, y);
dp[begin,end] = ans;
if (x >= y)
sell[begin,end] = 0;
else
sell[begin,end] = 1;
return ans;
}
// Util Function to calculate maxProfit
static int maxProfit(int []price, int n)
1697
Chapter 231. Maximum profit from sale of wines
{
int i, j;
// reseting the dp table
for(i = 0; i < N; i++)
for(j = 0; j < N; j++)
dp[i, j] = -1;
int ans = maxProfitUtil(price, 0,
n - 1, n);
i = 0; j = n - 1;
while (i <= j) {
// sell[i][j]=0 implies selling
// the wine from beginning will
// be more profitable in the
// long run
if(sell[i, j] == 0){
Console.Write( "beg ");
i++;
}
else
{
Console.Write( "end ");
j--;
}
}
Console.WriteLine();
return ans;
}
// Driver Code
public static void Main ()
{
// Price array
int []price = {2, 4, 6, 2, 5};
int n = price.Length;
int ans = maxProfit(price, n);
Console.WriteLine( ans );
}
}
// This code is contributed by anuj_67.
1698
Chapter 231. Maximum profit from sale of wines
Output:
Source
https://www.geeksforgeeks.org/maximum-profit-sale-wines/
1699
Chapter 232
Algorithm:
Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an auxiliary
size matrix S[][] in which each entry S[i][j] represents size of the square sub-matrix with all
1s including M[i][j] where M[i][j] is the rightmost and bottommost entry in sub-matrix.
1700
Chapter 232. Maximum size square sub-matrix with all 1s
sub-matrix of M[][]
For the given M[R][C] in above example, constructed S[R][C] would be:
0 1 1 0 1
1 1 0 1 0
0 1 1 1 0
1 1 2 2 0
1 2 2 3 1
0 0 0 0 0
The value of maximum entry in above matrix is 3 and coordinates of the entry are (4, 3).
Using the maximum value and its coordinates, we can find out the required sub-matrix.
C/C++
1701
Chapter 232. Maximum size square sub-matrix with all 1s
/* Find the maximum entry, and indexes of maximum entry
in S[][] */
max_of_s = S[0][0]; max_i = 0; max_j = 0;
for(i = 0; i < R; i++)
{
for(j = 0; j < C; j++)
{
if(max_of_s < S[i][j])
{
max_of_s = S[i][j];
max_i = i;
max_j = j;
}
}
}
printf("Maximum size sub-matrix is: \n");
for(i = max_i; i > max_i - max_of_s; i--)
{
for(j = max_j; j > max_j - max_of_s; j--)
{
printf("%d ", M[i][j]);
}
printf("\n");
}
}
/* UTILITY FUNCTIONS */
/* Function to get minimum of three values */
int min(int a, int b, int c)
{
int m = a;
if (m > b)
m = b;
if (m > c)
m = c;
return m;
}
/* Driver function to test above functions */
int main()
{
bool M[R][C] = {{0, 1, 1, 0, 1},
{1, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{1, 1, 1, 1, 0},
{1, 1, 1, 1, 1},
1702
Chapter 232. Maximum size square sub-matrix with all 1s
{0, 0, 0, 0, 0}};
printMaxSubSquare(M);
getchar();
}
Java
1703
Chapter 232. Maximum size square sub-matrix with all 1s
Python3
1704
Chapter 232. Maximum size square sub-matrix with all 1s
Output:
Time Complexity: O(m*n) where m is number of rows and n is number of columns in the
given matrix.
1705
Chapter 232. Maximum size square sub-matrix with all 1s
Auxiliary Space: O(m*n) where m is number of rows and n is number of columns in the
given matrix.
Algorithmic Paradigm: Dynamic Programming
Source
https://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/
1706
Chapter 233
This is the further enhancement to subset sum problem which not only tells whether the
subset is possible but also the maximal subset using DP.
To solve the subset sum problem, use the same DP approach as given in subset sum problem.
To further count the maximal subset, we use another DP array (called as ‘count array’) where
count[i][j] is maximal of
Java
1707
Chapter 233. Maximum size subset with given sum
1708
Chapter 233. Maximum size subset with given sum
{
int set[] = { 2, 3, 5, 10 };
int sum = 20;
int n = set.length;
System.out.println(isSubsetSum(set, n, sum));
}
}
C#
1709
Chapter 233. Maximum size subset with given sum
if (subset[i, j])
count[i, j] = Math.Max(count[i, j - 1],
count[i - set[j - 1], j - 1] + 1);
}
}
}
return count[sum, n];
}
/* Driver program to test above function */
public static void Main()
{
int[] set = { 2, 3, 5, 10 };
int sum = 20;
int n = set.Length;
Console.WriteLine(isSubsetSum(set, n, sum));
}
}
// This code is contributed by vt_m.
Output:
Source
https://www.geeksforgeeks.org/maximum-size-subset-given-sum/
1710
Chapter 234
Maximum sub-matrix area having count of 1’s one more than count of 0’s - GeeksforGeeks
Given a N x N binary matrix. The problem is finding the maximum area sub-matrix having
a count of 1’s one more than count of 0’s.
Examples:
Naive Approach: Check every possible rectangle in given 2D matrix. This solution re-
quires 4 nested loops and the time complexity of this solution would be O(n^4).
Efficient Approach: An efficient approach will be to use Longest subarray having count
of 1s one more than count of 0s which reduces the time complexity to O(n^3). The idea is
to fix the left and right columns one by one and find the maximum length contiguous rows
having the count of 1’s one more than the count of 0’s for every left and right column pair.
Find top and bottom row numbers (which have a maximum length) for every fixed left and
right column pair. To find the top and bottom row numbers, calculate the sum of elements
1711
Chapter 234. Maximum sub-matrix area having count of 1’s one more than count of 0’s
in every row from left to right and store these sums in an array say temp[] (consider 0 as -1
while adding it). So temp[i] indicates the sum of elements from left to right in row i. Using
the approach in Longest subarray having count of 1s one more than count of 0s , temp[]
array is used to get the maximum length subarray of temp[] having count of 1’s one more
than a count of 0’s by obtaining the start and end row numbers, then these values can be
used to find maximum possible area with left and right as boundary columns. To get the
overall maximum area, compare this area with the maximum area so far.
Below is the implementation of the above approach:
1712
Chapter 234. Maximum sub-matrix area having count of 1’s one more than count of 0’s
1713
Chapter 234. Maximum sub-matrix area having count of 1’s one more than count of 0’s
// Compare with maximum area
// so far and accordingly update the
// final variables
if ((len != 0) && (maxArea < (finish - start + 1)
* (right - left + 1))) {
finalLeft = left;
finalRight = right;
finalTop = start;
finalBottom = finish;
maxArea = (finish - start + 1) * (right - left + 1);
}
}
}
// Print final values
cout << "(Top, Left): (" << finalTop << ", "
<< finalLeft << ")\n";
cout << "(Bottom, Right): (" << finalBottom << ", "
<< finalRight << ")\n";
cout << "Maximum area: " << maxArea;
}
// Driver Code
int main()
{
int mat[SIZE][SIZE] = { { 1, 0, 0, 1 },
{ 0, 1, 1, 1 },
{ 1, 0, 0, 0 },
{ 0, 1, 0, 1 } };
int n = 4;
largestSubmatrix(mat, n);
return 0;
}
Output:
1714
Chapter 234. Maximum sub-matrix area having count of 1’s one more than count of 0’s
Source
https://www.geeksforgeeks.org/maximum-sub-matrix-area-having-count-of-1s-one-more-than-count-of-0s/
1715
Chapter 235
Examples:
Kadane’s Algorithm solves this problem using Dynamic Programming approach in linear
time. Here is another approach using Dynamic Programming and Prefix Sum to find out
maximum subarray sum in Linear time.
Prerequisite: Prefix Sum Array
1716
Chapter 235. Maximum subarray sum in O(n) using prefix sum
That is, we keep track of minimum prefix sum for x <= y and maximum
subarray sum so far.
Implementation:
1. Calculate the prefix sum of the input array.
2. Initialize : min_prefix_sum = 0, res = -infinite
3. Maintain a loop for i = 0 to n. (n is the size of the input array).
a) cand = prefix_sum[i] – mini
b) If cand is greater than res (maximum subarray sum so far), then update res by cand.
c) If prefix_sum[i] is less than min_prefix_sum (minimum prefix sum so far), then
update min_prefix_sum by prefix_sum[i].
4. Return res.
Reference: Algorithms for the problem of k maximum sums and a VLSI algorithm for the
k maximum subarrays problem
C++
1717
Chapter 235. Maximum subarray sum in O(n) using prefix sum
Java
1718
Chapter 235. Maximum subarray sum in O(n) using prefix sum
{
// Function to compute maximum
// subarray sum in linear time.
static int maximumSumSubarray(int arr[], int n)
{
// Initialize minimum
// prefix sum to 0.
int min_prefix_sum = 0;
// Initialize maximum subarray
// sum so far to -infinity.
int res = Integer.MIN_VALUE;
// Initialize and compute
// the prefix sum array.
int prefix_sum[] = new int[n];
prefix_sum[0] = arr[0];
for (int i = 1; i < n; i++)
prefix_sum[i] = prefix_sum[i - 1]
+ arr[i];
// loop through the array, keep
// track of minimum prefix sum so
// far and maximum subarray sum.
for (int i = 0; i < n; i++)
{
res = Math.max(res, prefix_sum[i] -
min_prefix_sum);
min_prefix_sum = Math.min(min_prefix_sum,
prefix_sum[i]);
}
return res;
}
// Driver Program
public static void main (String[] args)
{
// Test case 1
int arr1[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
int n1 = arr1.length;
System.out.println(maximumSumSubarray(arr1, n1));
// Test case 2
int arr2[] = { 4, -8, 9, -4, 1, -8, -1, 6 };
int n2 = arr2.length;
System.out.println(maximumSumSubarray(arr2, n2));
}
1719
Chapter 235. Maximum subarray sum in O(n) using prefix sum
}
// This code is contributed by Ansu Kumari.
Python3
1720
Chapter 235. Maximum subarray sum in O(n) using prefix sum
print(maximumSumSubarray(arr1, n1))
# Test case 2
arr2 = [ 4, -8, 9, -4, 1, -8, -1, 6 ]
n2 = len(arr2)
print(maximumSumSubarray(arr2, n2))
# This code is contributed by Ansu Kuamri.
C#
// C# program to find
// out maximum subarray
// sum in linear time
// using prefix sum.
using System;
class GFG
{
// Function to compute maximum
// subarray sum in linear time.
static int maximumSumSubarray(int []arr, int n)
{
// Initialize minimum
// prefix sum to 0.
int min_prefix_sum = 0;
// Initialize maximum subarray
// sum so far to -infinity.
int res = int.MinValue;
// Initialize and compute
// the prefix sum array.
int []prefix_sum = new int[n];
prefix_sum[0] = arr[0];
for (int i = 1; i < n; i++)
prefix_sum[i] = prefix_sum[i - 1]
+ arr[i];
// loop through the array, keep
// track of minimum prefix sum so
// far and maximum subarray sum.
for (int i = 0; i < n; i++)
{
res = Math.Max(res, prefix_sum[i] -
min_prefix_sum);
min_prefix_sum = Math.Min(min_prefix_sum,
prefix_sum[i]);
1721
Chapter 235. Maximum subarray sum in O(n) using prefix sum
}
return res;
}
// Driver Program
public static void Main ()
{
// Test case 1
int []arr1 = { -2, -3, 4, -1, -2, 1, 5, -3 };
int n1 = arr1.Length;
Console.WriteLine(maximumSumSubarray(arr1, n1));
// Test case 2
int []arr2 = { 4, -8, 9, -4, 1, -8, -1, 6 };
int n2 = arr2.Length;
Console.WriteLine(maximumSumSubarray(arr2, n2));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find out
// maximum subarray sum in
// linear time using prefix sum.
// Function to compute maximum
// subarray sum in linear time.
function maximumSumSubarray($arr, $n)
{
// Initialize minimum
// prefix sum to 0.
$min_prefix_sum = 0;
// Initialize maximum subarray
// sum so far to -infinity.
$res = PHP_INT_MIN;
// Initialize and compute
// the prefix sum array.
$prefix_sum = array();
$prefix_sum[0] = $arr[0];
for ($i = 1; $i < $n; $i++)
$prefix_sum[$i] = $prefix_sum[$i - 1] +
$arr[$i];
1722
Chapter 235. Maximum subarray sum in O(n) using prefix sum
// loop through the array,
// keep track of minimum
// prefix sum so far and
// maximum subarray sum.
for ($i = 0; $i < $n; $i++)
{
$res = max($res, $prefix_sum[$i] -
$min_prefix_sum);
$min_prefix_sum = min($min_prefix_sum,
$prefix_sum[$i]);
}
return $res;
}
// Driver Code
// Test case 1
$arr1 = array(-2, -3, 4, -1,
-2, 1, 5, -3);
$n1 = count($arr1);
echo maximumSumSubarray($arr1, $n1), " \n" ;
// Test case 2
$arr2 = array(4, -8, 9, -4,
1, -8, -1, 6);
$n2 = count($arr2);
echo maximumSumSubarray($arr2, $n2);
// This code is contributed by anuj_67.
?>
Output :
7
9
Time Complexity: O(n). It takes linear time to compute the prefix sum and takes
constant time in each iteration of the for loop. Hence overall complexity is O(n).
Improved By : vt_m
Source
https://www.geeksforgeeks.org/maximum-subarray-sum-using-prefix-sum/
1723
Chapter 236
A simple solution is to create an array of size n*k, then run Kadane’s algorithm. Time
complexity would be O(nk) and auxiliary space would be O(n*k)
A better solution is to run a loop on same array and use modular arithmetic to move
back beginning after end of array.
C++
1724
Chapter 236. Maximum subarray sum in an array created after repeated concatenation
Java
1725
Chapter 236. Maximum subarray sum in an array created after repeated concatenation
Python3
1726
Chapter 236. Maximum subarray sum in an array created after repeated concatenation
C#
1727
Chapter 236. Maximum subarray sum in an array created after repeated concatenation
PHP
<?php
// PHP program to print largest contiguous
// array sum when array is created after
// concatenating a small array k times.
1728
Chapter 236. Maximum subarray sum in an array created after repeated concatenation
// Returns sum of maximum
// sum subarray created
// after concatenating
// a[0..n-1] k times.
function maxSubArraySumRepeated($a, $n, $k)
{
$INT_MIN=0;
$max_so_far = $INT_MIN; $max_ending_here = 0;
for ($i = 0; $i < $n*$k; $i++)
{
// This is where it differs
// from Kadane's algorithm.
// We use modular arithmetic
// to find next element.
$max_ending_here = $max_ending_here +
$a[$i % $n];
if ($max_so_far < $max_ending_here)
$max_so_far = $max_ending_here;
if ($max_ending_here < 0)
$max_ending_here = 0;
}
return $max_so_far;
}
// Driver Code
$a = array(10, 20, -30, -1);
$n = sizeof($a);
$k = 3;
echo "Maximum contiguous sum is "
, maxSubArraySumRepeated($a, $n, $k);
// This code is contributed by nitin mittal.
?>
Output :
1729
Chapter 236. Maximum subarray sum in an array created after repeated concatenation
Source
https://www.geeksforgeeks.org/maximum-subarray-sum-array-created-repeated-concatenation/
1730
Chapter 237
1731
Chapter 237. Maximum subsequence sum such that no three are consecutive
sum[0] = arr[0]
In general,
// We have three cases
// 1) Exclude arr[i], i.e., sum[i] = sum[i-1]
// 2) Exclude arr[i-1], i.e., sum[i] = sum[i-2] + arr[i]
// 3) Exclude arr[i-2], i.e., sum[i-3] + arr[i] + arr[i-1]
sum[i] = max(sum[i-1], sum[i-2] + arr[i],
sum[i-3] + arr[i] + arr[i-1])
C/C++
1732
Chapter 237. Maximum subsequence sum such that no three are consecutive
if (n >= 1)
sum[0] = arr[0];
if (n >= 2)
sum[1] = arr[0] + arr[1];
if (n > 2)
sum[2] = max(sum[1], max(arr[1] + arr[2], arr[0] + arr[2]));
// Process rest of the elements
// We have three cases
// 1) Exclude arr[i], i.e., sum[i] = sum[i-1]
// 2) Exclude arr[i-1], i.e., sum[i] = sum[i-2] + arr[i]
// 3) Exclude arr[i-2], i.e., sum[i-3] + arr[i] + arr[i-1]
for (int i = 3; i < n; i++)
sum[i] = max(max(sum[i - 1], sum[i - 2] + arr[i]),
arr[i] + arr[i - 1] + sum[i - 3]);
return sum[n - 1];
}
// Driver code
int main()
{
int arr[] = { 100, 1000 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << maxSumWO3Consec(arr, n);
return 0;
}
Java
1733
Chapter 237. Maximum subsequence sum such that no three are consecutive
if (n >= 1)
sum[0] = arr[0];
if (n >= 2)
sum[1] = arr[0] + arr[1];
if (n > 2)
sum[2] = Math.max(sum[1], Math.max(arr[1] + arr[2], arr[0] + arr[2]));
// Process rest of the elements
// We have three cases
// 1) Exclude arr[i], i.e., sum[i] = sum[i-1]
// 2) Exclude arr[i-1], i.e., sum[i] = sum[i-2] + arr[i]
// 3) Exclude arr[i-2], i.e., sum[i-3] + arr[i] + arr[i-1]
for (int i = 3; i < n; i++)
sum[i] = Math.max(Math.max(sum[i - 1], sum[i - 2] + arr[i]),
arr[i] + arr[i - 1] + sum[i - 3]);
return sum[n - 1];
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 100, 1000, 100, 1000, 1 };
int n = arr.length;
System.out.println(maxSumWO3Consec(arr, n));
}
}
// This code is contributed by vt_m
Python
1734
Chapter 237. Maximum subsequence sum such that no three are consecutive
sum[0] = arr[0]
if n >= 2 :
sum[1] = arr[0] + arr[1]
if n > 2 :
sum[2] = max(sum[1], max(arr[1] + arr[2], arr[0] + arr[2]))
# Process rest of the elements
# We have three cases
# 1) Exclude arr[i], i.e., sum[i] = sum[i-1]
# 2) Exclude arr[i-1], i.e., sum[i] = sum[i-2] + arr[i]
# 3) Exclude arr[i-2], i.e., sum[i-3] + arr[i] + arr[i-1]
for i in range(3, n):
sum[i] = max(max(sum[i-1], sum[i-2] + arr[i]), arr[i] + arr[i-1] + sum[i-3])
return sum[n-1]
# Driver code
arr = [100, 1000, 100, 1000, 1]
n = len(arr)
print maxSumWO3Consec(arr, n)
# This code is contributed by Afzal Ansari
C#
1735
Chapter 237. Maximum subsequence sum such that no three are consecutive
sum[0] = arr[0];
if (n >= 2)
sum[1] = arr[0] + arr[1];
if (n > 2)
sum[2] = Math.Max(sum[1], Math.Max(arr[1] + arr[2], arr[0] + arr[2]));
// Process rest of the elements
// We have three cases
// 1) Exclude arr[i], i.e.,
// sum[i] = sum[i-1]
// 2) Exclude arr[i-1], i.e.,
// sum[i] = sum[i-2] + arr[i]
// 3) Exclude arr[i-2], i.e.,
// sum[i-3] + arr[i] + arr[i-1]
for (int i = 3; i < n; i++)
sum[i] = Math.Max(Math.Max(sum[i - 1],
sum[i - 2] + arr[i]),
arr[i] + arr[i - 1] + sum[i - 3]);
return sum[n - 1];
}
// Driver code
public static void Main()
{
int[] arr = { 100, 1000, 100, 1000, 1 };
int n = arr.Length;
Console.Write(maxSumWO3Consec(arr, n));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to find the maximum
// sum such that no three are consecutive
// Returns maximum subsequence
// sum such that no three
// elements are consecutive
function maxSumWO3Consec($arr, $n)
{
// Stores result for subarray
// arr[0..i], i.e., maximum
1736
Chapter 237. Maximum subsequence sum such that no three are consecutive
Output :
2101
1737
Chapter 237. Maximum subsequence sum such that no three are consecutive
Source
https://www.geeksforgeeks.org/maximum-subsequence-sum-such-that-no-three-are-consecutive/
1738
Chapter 238
This problem is a variation of standard Longest Increasing Subsequence (LIS) problem and
longest Bitonic Sub-sequence.
We construct two arrays MSIBS[] and MSDBS[]. MSIBS[i] stores the sum of the Increasing
subsequence ending with arr[i]. MSDBS[i] stores the sum of the Decreasing subsequence
starting from arr[i]. Finally, we need to return the max sum of MSIBS[i] + MSDBS[i] –
Arr[i].
Below is the implementation of above idea
1739
Chapter 238. Maximum sum Bi-tonic Sub-sequence
C/C++
1740
Chapter 238. Maximum sum Bi-tonic Sub-sequence
Java
1741
Chapter 238. Maximum sum Bi-tonic Sub-sequence
// return max sum of bi-tonic
// sub-sequence
return max_sum;
}
// Driver program
public static void main(String[] args)
{
int arr[] = { 1, 15, 51, 45, 33, 100, 12, 18, 9 };
int n = arr.length;
System.out.println("Maximum Sum : " + MaxSumBS(arr, n));
}
}
// This code is contributed by vt_m
Python
1742
Chapter 238. Maximum sum Bi-tonic Sub-sequence
for j in range(1, i):
if arr[-i] > arr[-j] and MSDBS[-i] < MSDBS[-j] + arr[-i]:
MSDBS[-i] = MSDBS[-j] + arr[-i]
max_sum = float("-Inf")
# Find the maximum value of MSIBS[i] + MSDBS[i] - arr[i]
for i, j, k in zip(MSIBS, MSDBS, arr):
max_sum = max(max_sum, i + j - k)
# return max sum of bi-tonic sub-sequence
return max_sum
# Driver program to test the above function
def main():
arr = [1, 15, 51, 45, 33, 100, 12, 18, 9]
n = len(arr)
print max_sum(arr, n)
if __name__ == '__main__':
main()
# This code is contributed by Neelam Yadav
C#
1743
Chapter 238. Maximum sum Bi-tonic Sub-sequence
PHP
<?php
// PHP program to find maximum
// sun of bi-tonic sub-sequence
1744
Chapter 238. Maximum sum Bi-tonic Sub-sequence
1745
Chapter 238. Maximum sum Bi-tonic Sub-sequence
}
// Driver Code
$arr = array(1, 15, 51, 45, 33,
100, 12, 18, 9);
$n = count($arr);
echo "Maximum Sum : " ,
MaxSumBS($arr, $n);
// This code is contributed
// by shiv_bhakt.
?>
Output:
Source
https://www.geeksforgeeks.org/maximum-sum-bi-tonic-sub-sequence/
1746
Chapter 239
This problem is similar to Longest Increasing Subsequence (LIS) problem. and can be solved
using Dynamic Programming.
1747
Chapter 239. Maximum sum alternating subsequence
1748
Chapter 239. Maximum sum alternating subsequence
// stores sum of decreasing and increasing
// sub-sequence
int dec[n];
memset(dec, 0, sizeof(dec));
// store sum of increasing and decreasing sun-sequence
int inc[n];
memset(inc, 0, sizeof(inc));
// As per question, first element must be part
// of solution.
dec[0] = inc[0] = arr[0];
int flag = 0 ;
// Traverse remaining elements of array
for (int i=1; i<n; i++)
{
for (int j=0; j<i; j++)
{
// IF current sub-sequence is decreasing the
// update dec[j] if needed. dec[i] by current
// inc[j] + arr[i]
if (arr[j] > arr[i])
{
dec[i] = max(dec[i], inc[j]+arr[i]);
// Revert the flag , if first decreasing
// is found
flag = 1;
}
// If next element is greater but flag should be 1
// i.e. this element should be counted after the
// first decreasing element gets counted
else if (arr[j] < arr[i] && flag == 1)
// If current sub-sequence is increasing
// then update inc[i]
inc[i] = max(inc[i], dec[j]+arr[i]);
}
}
// find maximum sum in b/w inc[] and dec[]
int result = INT_MIN;
for (int i = 0 ; i < n; i++)
{
1749
Chapter 239. Maximum sum alternating subsequence
Java
1750
Chapter 239. Maximum sum alternating subsequence
// of solution.
dec[0] = inc[0] = arr[0];
int flag = 0 ;
// Traverse remaining elements of array
for (int i=1; i<n; i++)
{
for (int j=0; j<i; j++)
{
// IF current sub-sequence is decreasing the
// update dec[j] if needed. dec[i] by current
// inc[j] + arr[i]
if (arr[j] > arr[i])
{
dec[i] = Math.max(dec[i], inc[j]+arr[i]);
// Revert the flag , if first decreasing
// is found
flag = 1;
}
// If next element is greater but flag should be 1
// i.e. this element should be counted after the
// first decreasing element gets counted
else if (arr[j] < arr[i] && flag == 1)
// If current sub-sequence is increasing
// then update inc[i]
inc[i] = Math.max(inc[i], dec[j]+arr[i]);
}
}
// find maximum sum in b/w inc[] and dec[]
int result = Integer.MIN_VALUE;
for (int i = 0 ; i < n; i++)
{
if (result < inc[i])
result = inc[i];
if (result < dec[i])
result = dec[i];
}
// return maximum sum alternate sun-sequence
return result;
}
// Driver Method
1751
Chapter 239. Maximum sum alternating subsequence
Python3
1752
Chapter 239. Maximum sum alternating subsequence
C#
1753
Chapter 239. Maximum sum alternating subsequence
1754
Chapter 239. Maximum sum alternating subsequence
Output:
Maximum sum = 25
1755
Chapter 239. Maximum sum alternating subsequence
Source
https://www.geeksforgeeks.org/maximum-sum-alternating-subsequence-sum/
1756
Chapter 240
Approach: The problem is closely related to Maximum Sum Bitonic Subsequence. We cre-
ate two arrays msis[] and msds[]. msis[i] stores the sum of Increasing subarray ending with
arr[i]. msds[i] stores the sum of Decreasing subarray starting from arr[i]. Now, maximum
sum bitonic subarray is calculated as max(msis[i]+msds[i]-arr[i]) for each index i of the
array.
C++
1757
Chapter 240. Maximum sum bitonic subarray
1758
Chapter 240. Maximum sum bitonic subarray
Java
1759
Chapter 240. Maximum sum bitonic subarray
Python 3
# Python 3 implementation
# to find the maximum sum
# bitonic subarray
# function to find the
# maximum sum bitonic subarray
def maxSumBitonicSubArr(arr, n):
# 'msis[]' to store the maximum
# sum increasing subarray up to
# each index of 'arr' from the
1760
Chapter 240. Maximum sum bitonic subarray
1761
Chapter 240. Maximum sum bitonic subarray
C#
// C# implementation to find
// the maximum sum bitonic subarray
using System;
class GFG
{
// function to find the maximum
// sum bitonic subarray
static int maxSumBitonicSubArr(int[] arr,
int n)
{
// 'msis[]' to store the maximum
// sum increasing subarray up to
// each index of 'arr' from the
// beginning 'msds[]' to store
// the maximum sum decreasing
// subarray from each index of
// 'arr' up to the end
int []msis = new int[n];
int []msds = new int[n];
// to store the maximum
// sum bitonic subarray
int max_sum = int.MinValue;
// building up the maximum
// sum increasing subarray
// for each array index
msis[0] = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > arr[i - 1])
msis[i] = msis[i - 1] +
arr[i];
else
msis[i] = arr[i];
// building up the maximum
1762
Chapter 240. Maximum sum bitonic subarray
PHP
<?php
// PHP implementation to find the
// maximum sum bitonic subarray
// function to find the maximum sum
// bitonic subarray
function maxSumBitonicSubArr($arr, $n)
1763
Chapter 240. Maximum sum bitonic subarray
{
// 'msis[]' to store the maximum
// sum increasing subarray up to
// each index of 'arr' from the
// beginning 'msds[]' to store
// the maximum sum decreasing
// subarray from each index of
// 'arr' up to the end
$msis = array();
$msds = array();
// to store the maximum
// sum bitonic subarray
$max_sum = PHP_INT_MIN;
// building up the maximum
// sum increasing subarray
// for each array index
$msis[0] = $arr[0];
for ($i = 1; $i < $n; $i++)
if ($arr[$i] > $arr[$i - 1])
$msis[$i] = $msis[$i - 1] +
$arr[$i];
else
$msis[$i] = $arr[$i];
// building up the maximum
// sum decreasing subarray
// for each array index
$msds[$n - 1] = $arr[$n - 1];
for ($i = $n - 2; $i >= 0; $i--)
if ($arr[$i] > $arr[$i + 1])
$msds[$i] = $msds[$i + 1] +
$arr[$i];
else
$msds[$i] = $arr[$i];
// for each array index,
// calculating the maximum sum
// of bitonic subarray of which
// it is a part of
for ($i = 0; $i < $n; $i++)
// if true , then update
// 'max' bitonic subarray sum
if ($max_sum < ($msis[$i] +
$msds[$i] - $arr[$i]))
$max_sum = $msis[$i] +
$msds[$i] - $arr[$i];
1764
Chapter 240. Maximum sum bitonic subarray
// required maximum sum
return $max_sum;
}
// Driver Code
$arr = array(5, 3, 9,
2, 7, 6, 4);
$n = sizeof($arr);
echo "Maximum Sum = ",
maxSumBitonicSubArr($arr, $n);
// This code is contributed by ajit
?>
Output:
Maximum Sum = 19
1765
Chapter 240. Maximum sum bitonic subarray
1766
Chapter 240. Maximum sum bitonic subarray
1767
Chapter 240. Maximum sum bitonic subarray
Output:
Maximum Sum = 19
Maximum Sum = 15
Maximum Sum = 15
Maximum Sum = 5
Maximum Sum = 7
Maximum Sum = 4
Source
https://www.geeksforgeeks.org/maximum-sum-bitonic-subarray/
1768
Chapter 241
Maximum sum in a 2 x n grid such that no two elements are adjacent - GeeksforGeeks
Given a rectangular grid of dimension 2 x n. We need to find out the maximum sum such
that no two chosen numbers are adjacent, vertically, diagonally or horizontally.
Examples:
Input : 1 4 5
2 0 0
Output : 7
If we start from 1 then we can add only 5 or 0.
So max_sum = 6 in this case.
If we select 2 then also we can add only 5 or 0.
So max_sum = 7 in this case.
If we select from 4 or 0 then there is no further
elements can be added.
So, Max sum is 7.
Input : 1 2 3 4 5
6 7 8 9 10
Output : 24
This problem is an extension of Maximum sum such that no two elements are adjacent.
Only thing to be changed is to take maximum element of both row of a particular column.
We traverse column by column and maintain maximum sum considering two cases.
1) An element of current column is included. In this case we take maximum of two elements
1769
Chapter 241. Maximum sum in a 2 x n grid such that no two elements are adjacent
in current column.
2) An element of current column is excluded (or not included)
Below is the implementation of above steps.
C++
1770
Chapter 241. Maximum sum in a 2 x n grid such that no two elements are adjacent
int n = 5;
cout << maxSum(grid, n);
return 0;
}
Java
1771
Chapter 241. Maximum sum in a 2 x n grid such that no two elements are adjacent
{ 6, 7, 8, 9, 10}};
int n = 5;
System.out.println(maxSum(grid, n));
}
}
// This code is contributed by Arnav Kr. Mandal.
Output:
24
Source
https://www.geeksforgeeks.org/maximum-sum-2-x-n-grid-no-two-elements-adjacent/
1772
Chapter 242
Maximum sum in circular array such that no two elements are adjacent - GeeksforGeeks
Given a circular array containing of positive integers value. The task is to find the maximum
sum of a subsequence with the constraint that no 2 numbers in the sequence should be
adjacent in the array.
Examples:
Approach The problem can be solved using DP. An approach has already been discussed
in thispost, but it for an array. We can treat the circular subarray a two arrays one from
(0th to n-2-th) and (1st to n-1-th) index, and use the approach used in the previous post.
The maximum sum returned by both will be the answer.
1773
Chapter 242. Maximum sum in circular array such that no two elements are adjacent
1774
Chapter 242. Maximum sum in circular array such that no two elements are adjacent
1775
Chapter 242. Maximum sum in circular array such that no two elements are adjacent
// bootom-up approach
for (int j = 1; j < i - 1; j++) {
// dp condition
if (dp[i] < arr[i] + dp[j]) {
dp[i] = arr[i] + dp[j];
// find max sum
if (maxi < dp[i])
maxi = dp[i];
}
}
}
// return max
return maxi;
}
int findMaxSum(int arr[], int n)
{
return max(maxSum1(arr, n), maxSum2(arr, n));
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 3, 1 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << findMaxSum(arr, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/maximum-sum-in-circular-array-such-that-no-two-elements-are-adjacent/
1776
Chapter 243
Maximum sum increasing subsequence from a prefix and a given element after prefix is must
- GeeksforGeeks
Given an array of n positive integers, write a program to find the maximum sum of increasing
subsequence from prefix till i-th index and also including a given kth element which is after
i, i.e., k > i .
Examples :
1777
Chapter 243. Maximum sum increasing subsequence from a prefix and a given element
after prefix is must
Simple Approach:
1. Construct a new array containing elements till ith index and the kth element.
2. Recursively calculate all the increasing subsequences.
3. Discard all the subsequences not having kth element included.
4. Calculate the maximum sum from the left over subsequences and display it.
C++
1778
Chapter 243. Maximum sum increasing subsequence from a prefix and a given element
after prefix is must
// To calculate for i=4 and k=6.
return dp[index][k];
}
int main()
{
ll a[] = { 1, 101, 2, 3, 100, 4, 5 };
ll n = sizeof(a) / sizeof(a[0]);
ll index = 4, k = 6;
printf("%lld", pre_compute(a, n, index, k));
return 0;
}
Java
1779
Chapter 243. Maximum sum increasing subsequence from a prefix and a given element
after prefix is must
}
else
dp[i][j] = dp[i - 1][j];
}
}
// To calculate for i=4 and k=6.
return dp[index][k];
}
// Driver code
public static void main(String[] args)
{
int a[] = { 1, 101, 2, 3, 100, 4, 5 };
int n = a.length;
int index = 4, k = 6;
System.out.println(
pre_compute(a, n, index, k));
}
}
// This code is contributed by Smitha.
C#
1780
Chapter 243. Maximum sum increasing subsequence from a prefix and a given element
after prefix is must
Output:
11
1781
Chapter 243. Maximum sum increasing subsequence from a prefix and a given element
after prefix is must
To try similar problem, give this article a read: Maximum product of an increasing subse-
quence
Improved By : Smitha Dinesh Semwal, jit_t
Source
https://www.geeksforgeeks.org/maximum-sum-increasing-subsequence-from-a-prefix-and-a-given-element-after-pre
1782
Chapter 244
Input : 1
1 2
4 1 2
2 3 1 1
Output : 9
Explanation : 1 + 1 + 4 + 3
Input : 2
4 1
1 2 7
Output : 10
Explanation : 2 + 1 + 7
The idea is to find largest sum ending at every cell of last row and return maximum of
these sums. We can recursively compute these sums by recursively considering above two
cells. Since there are overlapping subproblems, we use dynamic programming to find the
maximum sum ending at particular cell of last row.
Below is the implementation of above idea.
C++
1783
Chapter 244. Maximum sum of a path in a Right Number Triangle
1784
Chapter 244. Maximum sum of a path in a Right Number Triangle
return max;
}
// driver program
int main(){
int tri[3][3] = {{1}, {2,1}, {3,3,2}};
cout<<maxSum(tri, 3);
return 0;
}
Java
1785
Chapter 244. Maximum sum of a path in a Right Number Triangle
tri[i][j] = tri[i][j]
+ tri[i-1][j-1];
else
tri[i][j] = tri[i][j]
+ tri[i-1][j];
}
}
// array at n-1 index (tri[i]) stores
// all possible adding combination,
// finding the maximum one out of them
int max = tri[n-1][0];
for(int i = 1; i < n; i++)
{
if(max < tri[n-1][i])
max = tri[n-1][i];
}
return max;
}
// Driver code
public static void main (String[] args)
{
int tri[][] = {{1}, {2,1}, {3,3,2}};
System.out.println(maxSum(tri, 3));
}
}
// This code is contributed by Anant Agarwal.
Python
1786
Chapter 244. Maximum sum of a path in a Right Number Triangle
tri[1][1] = tri[1][1]+tri[0][0]
tri[1][0] = tri[1][0]+tri[0][0]
# Traverse remaining rows
for i in range(2, n):
tri[i][0] = tri[i][0] + tri[i-1][0]
tri[i][i] = tri[i][i] + tri[i-1][i-1]
# Loop to traverse columns
for j in range(1, i):
# Checking the two conditions, directly below
# and below right. Considering the greater one
# tri[i] would store the possible combinations
# of sum of the paths
if tri[i][j]+tri[i-1][j-1] >= tri[i][j]+tri[i-1][j]:
tri[i][j] = tri[i][j] + tri[i-1][j-1]
else:
tri[i][j] = tri[i][j]+tri[i-1][j]
# array at n-1 index (tri[i]) stores all possible
# adding combination, finding the maximum one
# out of them
print max(tri[n-1])
# driver program
tri = [[1], [2,1], [3,3,2]]
maxSum(tri, 3)
C#
// C# program to print
// maximum sum in a right
// triangle of numbers
using System;
class GFG
{
// function to find
// maximum sum path
static int maxSum(int [,]tri,
int n)
{
// Adding the element of row 1
// to both the elements of row 2
1787
Chapter 244. Maximum sum of a path in a Right Number Triangle
1788
Chapter 244. Maximum sum of a path in a Right Number Triangle
return max;
}
// Driver Code
public static void Main ()
{
int [,]tri = {{1,0,0},
{2,1,0},
{3,3,2}};
Console.Write(maxSum(tri, 3));
}
}
// This code is contributed by ajit.
PHP
<?php
// PHP program to print maximum sum
// in a right triangle of numbers
// function to find maximum sum path
function maxSum($tri, $n)
{
// Adding the element of row 1
// to both the elements of row
// 2 to reduce a step from the loop
if ($n > 1)
$tri[1][1] = $tri[1][1] + $tri[0][0];
$tri[1][0] = $tri[1][0] + $tri[0][0];
// Traverse remaining rows
for($i = 2; $i < $n; $i++)
{
$tri[$i][0] = $tri[$i][0] +
$tri[$i - 1][0];
$tri[$i][$i] = $tri[$i][$i] +
$tri[$i - 1][$i - 1];
//Loop to traverse columns
for ($j = 1; $j < $i; $j++)
{
// Checking the two conditions,
// directly below and below right.
1789
Chapter 244. Maximum sum of a path in a Right Number Triangle
Output :
Improved By : jit_t
1790
Chapter 244. Maximum sum of a path in a Right Number Triangle
Source
https://www.geeksforgeeks.org/maximum-sum-path-right-number-triangle/
1791
Chapter 245
First we sort the given array in increasing order. Once array is sorted, we traverse the
array. For every element, we try to pair it with its previous element first. Why do we prefer
previous element? Let arr[i] can be paired with arr[i-1] and arr[i-2] (i.e. arr[i] – arr[i-1] <
K and arr[i]-arr[i-2] < K). Since the array is sorted, value of arr[i-1] would be more than
arr[i-2]. Also, we need to pair with difference less than k, it means if arr[i-2] can be paired,
then arr[i-1] can also be paired in a sorted array.
Now observing the above facts, we can formulate our dynamic programming solution as
below,
Let dp[i] denotes the maximum disjoint pair sum we can achieve using first i elements of
the array. Assume currently we are at i’th position, then there are two possibilities for us.
1792
Chapter 245. Maximum sum of pairs with specific difference
Above iteration takes O(N) time and sorting of array will take O(N log N) time so total
time complexity of the solution will be O(N log N)
C++
1793
Chapter 245. Maximum sum of pairs with specific difference
// last index will have the result
return dp[N - 1];
}
// Driver code to test above methods
int main()
{
int arr[] = {3, 5, 10, 15, 17, 12, 9};
int N = sizeof(arr)/sizeof(int);
int K = 4;
cout << maxSumPairWithDifferenceLessThanK(arr, N, K);
return 0;
}
Java
1794
Chapter 245. Maximum sum of pairs with specific difference
Python3
1795
Chapter 245. Maximum sum of pairs with specific difference
# i elements
dp = [0] * N
# if no element then dp value will be 0
dp[0] = 0
for i in range(1, N):
# first give previous value to
# dp[i] i.e. no pairing with
# (i-1)th element
dp[i] = dp[i-1]
# if current and previous element
# can form a pair
if (arr[i] - arr[i-1] < K):
# update dp[i] by choosing
# maximum between pairing
# and not pairing
if (i >= 2):
dp[i] = max(dp[i], dp[i-2] + arr[i] + arr[i-1]);
else:
dp[i] = max(dp[i], arr[i] + arr[i-1]);
# last index will have the result
return dp[N - 1]
# Driver code to test above methods
arr = [3, 5, 10, 15, 17, 12, 9]
N = len(arr)
K = 4
print(maxSumPairWithDifferenceLessThanK(arr, N, K))
# This code is contributed by Smitha Dinesh Semwal
C#
1796
Chapter 245. Maximum sum of pairs with specific difference
{
// Sort input array in ascending order.
Array.Sort(arr);
// dp[i] denotes the maximum disjoint pair sum
// we can achieve using first i elements
int []dp = new int[N];
// if no element then dp value will be 0
dp[0] = 0;
for (int i = 1; i < N; i++)
{
// first give previous value to dp[i] i.e.
// no pairing with (i-1)th element
dp[i] = dp[i-1];
// if current and previous element can form
// a pair
if (arr[i] - arr[i-1] < K)
{
// update dp[i] by choosing maximum
// between pairing and not pairing
if (i >= 2)
dp[i] = Math.Max(dp[i], dp[i-2]
+ arr[i] + arr[i-1]);
else
dp[i] = Math.Max(dp[i], arr[i]
+ arr[i-1]);
}
}
// last index will have the result
return dp[N - 1];
}
// Driver code to test above methods
public static void Main () {
int []arr = {3, 5, 10, 15, 17, 12, 9};
int N = arr.Length;
int K = 4;
Console.WriteLine(
maxSumPairWithDifferenceLessThanK(arr, N, K));
1797
Chapter 245. Maximum sum of pairs with specific difference
}
}
// This code is contributed by anuj_67.
Output:
62
C++
1798
Chapter 245. Maximum sum of pairs with specific difference
maxSum += arr[i-1];
//When a match is found skip this pair
--i;
}
}
return maxSum;
}
// Driver code to test above methods
int main()
{
int arr[] = {3, 5, 10, 15, 17, 12, 9};
int N = sizeof(arr)/sizeof(int);
int K = 4;
cout << maxSumPairWithDifferenceLessThanK(arr, N, K);
return 0;
}
Java
1799
Chapter 245. Maximum sum of pairs with specific difference
C#
1800
Chapter 245. Maximum sum of pairs with specific difference
1801
Chapter 245. Maximum sum of pairs with specific difference
}
// This code is contributed by nitin mittal.
Output:
62
Source
https://www.geeksforgeeks.org/maximum-sum-pairs-specific-difference/
1802
Chapter 246
{5, 6, 1, 7},
{-2, 10, 8, -1},
{3, -7, -9, 11},
{12, -4, 2, 6} }
Algorithm: The idea is to find maximum sum or all paths starting with every cell of first
row and finally return maximum of all values in first row. We use Dynamic Programming
as results of many subproblems are needed again and again.
C++
1803
Chapter 246. Maximum sum path in a matrix from top to bottom
1804
Chapter 246. Maximum sum path in a matrix from top to bottom
maxSum = dp[0][j];
// required maximum sum
return maxSum;
}
// Driver program to test above
int main()
{
int mat[SIZE][SIZE] = { { 5, 6, 1, 7 },
{ -2, 10, 8, -1 },
{ 3, -7, -9, 11 },
{ 12, -4, 2, 6 } };
int n = 4;
cout << "Maximum Sum = "
<< maxSum(mat, n);
return 0;
}
Java
1805
Chapter 246. Maximum sum path in a matrix from top to bottom
1806
Chapter 246. Maximum sum path in a matrix from top to bottom
C#
1807
Chapter 246. Maximum sum path in a matrix from top to bottom
PHP
<?php
// PHP implementation to find
// the maximum sum path in a matrix
$SIZE = 10;
// function to find the maximum sum
// path in a matric
function maxSum( $mat, $n)
{
// if there is a single
// element only
if ($n == 1)
return $mat[0][0];
1808
Chapter 246. Maximum sum path in a matrix from top to bottom
// dp[][] matrix to store the results
// of each iteration
$dp = array(array());
$maxSum = PHP_INT_MIN;
$max;
// base case, copying elements of
// last row
for($j = 0; $j < $n; $j++)
$dp[$n - 1][$j] = $mat[$n - 1][$j];
// building up the dp[][] matrix from
// bottom to the top row
for ( $i = $n - 2; $i >= 0; $i--)
{
for ( $j = 0; $j < $n; $j++)
{
$max = PHP_INT_MIN;
// finding the maximum
// diagonal element in the
// (i+1)th row if that cell
// exists
if ((($j - 1) >= 0) and
($max < $dp[$i + 1][$j - 1]))
$max = $dp[$i + 1][$j - 1];
if ((($j + 1) < $n) and ($max <
$dp[$i + 1][$j + 1]))
$max = $dp[$i + 1][$j + 1];
// adding that 'max' element to the
// mat[i][j] element
$dp[$i][$j] = $mat[$i][$j] + $max;
}
}
// finding the maximum value from the
// first row of dp[][]
for ( $j = 0; $j < $n; $j++)
if ($maxSum < $dp[0][$j])
$maxSum = $dp[0][$j];
// required maximum sum
return $maxSum;
1809
Chapter 246. Maximum sum path in a matrix from top to bottom
}
// Driver Code
$mat = array(array(5, 6, 1, 7),
array(-2, 10, 8, -1),
array(3, -7, -9, 11),
array(12, -4, 2, 6));
$n = 4;
echo "Maximum Sum = "
, maxSum($mat, $n);
// This code is contributed by anuj_67.
?>
Output:
Maximum Sum = 28
Source
https://www.geeksforgeeks.org/maximum-sum-path-matrix-top-bottom/
1810
Chapter 247
If element removal condition is not applied, we can solve this problem using Kadane’s
algorithm but here one element can be removed also for increasing maximum sum. This
condition can be handled using two arrays, forward and backward array, these arrays store
the current maximum subarray sum from starting to ith index, and from ith index to
ending respectively.
In below code, two loops are written, first one stores maximum current sum in forward
direction in fw[] and other loop stores the same in backward direction in bw[]. Getting
current maximum and updation is same as Kadane’s algorithm.
Now when both arrays are created, we can use them for one element removal conditions as
follows, at each index i, maximum subarray sum after ignoring i’th element will be fw[i-1]
+ bw[i+1] so we loop for all possible i values and we choose maximum among them.
1811
Chapter 247. Maximum sum subarray removing at most one element
C/C++
1812
Chapter 247. Maximum sum subarray removing at most one element
Java
1813
Chapter 247. Maximum sum subarray removing at most one element
Python
1814
Chapter 247. Maximum sum subarray removing at most one element
# Method returns maximum sum of all subarray where
# removing one element is also allowed
def maxSumSubarrayRemovingOneEle(arr, n):
# Maximum sum subarrays in forward and backward
# directions
fw = [0 for k in range(n)]
bw = [0 for k in range(n)]
# Initialize current max and max so far.
cur_max, max_so_far = arr[0], arr[0]
# calculating maximum sum subarrays in forward
# direction
for i in range(n):
cur_max = max(arr[i], cur_max + arr[i])
max_so_far = max(max_so_far, cur_max)
# storing current maximum till ith, in
# forward array
fw[i] = cur_max
# calculating maximum sum subarrays in backward
# direction
cur_max = max_so_far = bw[n-1] = arr[n-1]
i = n-2
while i >= 0:
cur_max = max(arr[i], cur_max + arr[i])
max_so_far = max(max_so_far, cur_max)
# storing current maximum from ith, in
# backward array
bw[i] = cur_max
i -= 1
# Initializing final ans by max_so_far so that,
# case when no element is removed to get max sum
# subarray is also handled
fans = max_so_far
# choosing maximum ignoring ith element
for i in range(1,n-1):
fans = max(fans, fw[i - 1] + bw[i + 1])
return fans
# Driver code to test above methods
arr = [-2, -3, 4, -1, -2, 1, 5, -3]
1815
Chapter 247. Maximum sum subarray removing at most one element
n = len(arr)
print maxSumSubarrayRemovingOneEle(arr, n)
# Contributed by: Afzal_Saan
C#
1816
Chapter 247. Maximum sum subarray removing at most one element
// storing current maximum from ith, in
// backward array
bw[i] = cur_max;
}
/* Initializing final ans by max_so_far so that,
case when no element is removed to get max sum
subarray is also handled */
int fans = max_so_far;
// choosing maximum ignoring ith element
for (int i = 1; i < n - 1; i++)
fans = Math.Max(fans, fw[i - 1] + bw[i + 1]);
return fans;
}
// Driver code
public static void Main()
{
int []arr = { -2, -3, 4, -1, -2, 1, 5, -3 };
int n = arr.Length;
Console.WriteLine(maxSumSubarrayRemovingOneEle(
arr, n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to get maximum
// sum subarray removing
// at-most one element
// Method returns maximum sum
// of all subarray where removing
// one element is also allowed
function maxSumSubarrayRemovingOneEle( $arr, $n)
{
// Maximum sum subarrays in
// forward and backward directions
$fw = array(); $bw = array();
// Initialize current
1817
Chapter 247. Maximum sum subarray removing at most one element
1818
Chapter 247. Maximum sum subarray removing at most one element
return $fans;
}
// Driver Code
$arr = array(-2, -3, 4, -1,
-2, 1, 5, -3);
$n = count($arr);
echo maxSumSubarrayRemovingOneEle($arr, $n);
// This code is contributed by anuj_67.
?>
Output :
Source
https://www.geeksforgeeks.org/maximum-sum-subarray-removing-one-element/
1819
Chapter 248
1820
Chapter 248. Maximum sum subsequence with at-least k distant elements
1. If we select element at index i such that i + k + 1 >= N, then we cannot select any
other element as part of the subsequence. Hence we need to decide whether to select
this element or one of the elements after it.
2. If we select element at index i such that i + k + 1 < N, then the next element we
can select is at i + k + 1 index. Thus we need to decide whether to select these two
elements, or move on to the next adjacent element.
Base Case:
MS[N-1] = arr[N-1]
If i + 1 + k >= N
MS[i] = max(arr[i], MS[i+1]),
Else
MS[i] = max(arr[i] + MS[i+k+1], MS[i+1])
C++
1821
Chapter 248. Maximum sum subsequence with at-least k distant elements
}
return MS[0];
}
// Driver code
int main()
{
int N = 10, k = 2;
int arr[] = { 50, 70, 40, 50, 90, 70, 60, 40, 70, 50 };
cout << maxSum(arr, N, k);
return 0;
}
Java
1822
Chapter 248. Maximum sum subsequence with at-least k distant elements
40, 70, 50 };
System.out.println(maxSum(arr, N, k));
}
}
// This code is contributed by Prerna Saini
Python3
# Python3 program to find maximum
# sum subsequence such that elements
# are at least k distance away.
def maxSum(arr, N, k):
# MS[i] is going to store maximum sum
# subsequence in subarray from arr[i]
# to arr[n-1]
MS = [0 for i in range(N)]
# We fill MS from right to left.
MS[N - 1] = arr[N - 1]
for i in range(N - 2, -1, -1):
if (i + k + 1 >= N):
MS[i] = max(arr[i], MS[i + 1])
else:
MS[i] = max(arr[i] + MS[i + k + 1],
MS[i + 1])
return MS[0]
# Driver code
N = 10; k = 2
arr = [ 50, 70, 40, 50, 90, 70, 60, 40, 70, 50 ]
print(maxSum(arr, N, k))
# This code is contributed by Anant Agarwal.
C#
1823
Chapter 248. Maximum sum subsequence with at-least k distant elements
PHP
<?php
// PHP program to find
// maximum sum subsequence
// such that elements are
// at least k distance
// away.
function maxSum($arr, $N, $k)
{
// MS[i] is going to
// store maximum sum
// subsequence in
1824
Chapter 248. Maximum sum subsequence with at-least k distant elements
Output:
230
Source
https://www.geeksforgeeks.org/maximum-sum-subsequence-least-k-distant-elements/
1825
Chapter 249
Algorithm:
Loop for all elements in arr[] and maintain two sums incl and excl where incl = Max sum
including the previous element and excl = Max sum excluding the previous element.
Max sum excluding the current element will be max(incl, excl) and max sum including the
current element will be excl + current element (Note that only excl is considered because
elements cannot be adjacent).
At the end of the loop return max of incl and excl.
Example:
1826
Chapter 249. Maximum sum such that no two elements are adjacent
incl = 5
excl = 0
C/C++
#include<stdio.h>
/*Function to return max sum such that no two elements
are adjacent */
int FindMaxSum(int arr[], int n)
{
int incl = arr[0];
int excl = 0;
int excl_new;
int i;
for (i = 1; i < n; i++)
{
/* current max excluding i */
excl_new = (incl > excl)? incl: excl;
1827
Chapter 249. Maximum sum such that no two elements are adjacent
/* current max including i */
incl = excl + arr[i];
excl = excl_new;
}
/* return max of incl and excl */
return ((incl > excl)? incl : excl);
}
/* Driver program to test above function */
int main()
{
int arr[] = {5, 5, 10, 100, 10, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d n", FindMaxSum(arr, n));
return 0;
}
Java
class MaximumSum
{
/*Function to return max sum such that no two elements
are adjacent */
int FindMaxSum(int arr[], int n)
{
int incl = arr[0];
int excl = 0;
int excl_new;
int i;
for (i = 1; i < n; i++)
{
/* current max excluding i */
excl_new = (incl > excl) ? incl : excl;
/* current max including i */
incl = excl + arr[i];
excl = excl_new;
}
/* return max of incl and excl */
return ((incl > excl) ? incl : excl);
}
// Driver program to test above functions
public static void main(String[] args)
1828
Chapter 249. Maximum sum such that no two elements are adjacent
{
MaximumSum sum = new MaximumSum();
int arr[] = new int[]{5, 5, 10, 100, 10, 5};
System.out.println(sum.FindMaxSum(arr, arr.length));
}
}
// This code has been contributed by Mayank Jaiswal
Python
C#
1829
Chapter 249. Maximum sum such that no two elements are adjacent
{
int incl = arr[0];
int excl = 0;
int excl_new;
int i;
for (i = 1; i < n; i++)
{
/* current max excluding i */
excl_new = (incl > excl) ?
incl : excl;
/* current max including i */
incl = excl + arr[i];
excl = excl_new;
}
/* return max of incl and excl */
return ((incl > excl) ?
incl : excl);
}
// Driver program to test above
// functions
public static void Main()
{
int []arr = new int[]{5, 5, 10,
100, 10, 5};
Console.Write(
FindMaxSum(arr, arr.Length));
}
}
// This code has been contributed by
// nitin mittal
PHP
<?php
// PHP code to find Maximum sum
// such that no two elements
// are adjacent
/* Function to return max sum
such that no two elements
are adjacent */
function FindMaxSum($arr, $n)
1830
Chapter 249. Maximum sum such that no two elements are adjacent
{
$incl = $arr[0];
$excl = 0;
$excl_new;
$i;
for ($i = 1; $i <$n; $i++)
{
// current max excluding i
$excl_new = ($incl > $excl)? $incl: $excl;
// current max including i
$incl = $excl + $arr[$i];
$excl = $excl_new;
}
// return max of incl and excl
return (($incl > $excl)? $incl : $excl);
}
// Driver Code
$arr = array(5, 5, 10, 100, 10, 5);
$n = sizeof($arr);
echo FindMaxSum($arr, $n);
// This code is contributed by Ajit
?>
Output:
110
Source
https://www.geeksforgeeks.org/maximum-sum-such-that-no-two-elements-are-adjacent/
1831
Chapter 250
Input : n = 10
Output : MaxSum = 12
Explanation:
f(10) = f(10/2) + f(10/3) + f(10/4) + f(10/5)
= f(5) + f(3) + f(2) + f(2)
= 12
5, 3 and 2 cannot be further divided.
Input : n = 2
Output : MaxSum = 2
Approach : This problem can be solve with recursive approach but that will cost us a high
complexity because of its overlapping sub problems. So we apply dynamic programming
concept to solve this question in bottom up manner as:
C++
1832
Chapter 250. Maximum value with the choice of either dividing or considering as it is
Java
1833
Chapter 250. Maximum value with the choice of either dividing or considering as it is
Python3
C#
1834
Chapter 250. Maximum value with the choice of either dividing or considering as it is
PHP
<?php
// PHP program to maximize
// result when we have choice
// to divide or consider as it is.
// function for calculating
// max possible result
function maxDP ($n)
{
$res[0] = 0;
$res[1] = 1;
1835
Chapter 250. Maximum value with the choice of either dividing or considering as it is
// Compute remaining values
// in bottom up manner.
for ($i = 2; $i <= $n; $i++)
$res[$i] = max($i, ($res[$i / 2] +
$res[$i / 3] +
$res[$i / 4] +
$res[$i / 5]));
return $res[$n];
}
// Driver Code
$n = 60;
echo "MaxSum =", maxDP ($n);
// This code is contributed by aj_36
?>
Output :
MaxSum = 106
Improved By : jit_t
Source
https://www.geeksforgeeks.org/maximum-value-choice-either-dividing-considering/
1836
Chapter 251
Maximum weight path ending at any element of last row in a matrix - GeeksforGeeks
Given a matrix of integers where every element represents weight of the cell. Find the path
having the maximum weight in matrix [N X N]. Path Traversal Rules are:
Examples:
Input : N = 5
mat[5][5] = {{ 4, 2 ,3 ,4 ,1 },
{ 2 , 9 ,1 ,10 ,5 },
{15, 1 ,3 , 0 ,20 },
{16 ,92, 41, 44 ,1},
{8, 142, 6, 4, 8} };
Output : 255
Path with max weight : 4 + 2 +15 + 92 + 142 = 255
1837
Chapter 251. Maximum weight path ending at any element of last row in a matrix
If i == 0 and j == 0
maxCost(0, 0) = mat[0][0]
If we draw recursion tree of above recursive solution, we can observe overlapping subprob-
lems. Since the problem has overlapping subproblems, we can solve it efficiently using
Dynamic Programming. Below is Dynamic Programming based solution.
C++
1838
Chapter 251. Maximum weight path ending at any element of last row in a matrix
Java
1839
Chapter 251. Maximum weight path ending at any element of last row in a matrix
dp[0][0] = mat[0][0];
// Initialize first column of total
// weight array (dp[i to N][0])
for (int i = 1; i < N; i++)
dp[i][0] = mat[i][0] + dp[i-1][0];
// Calculate rest path sum of weight matrix
for (int i = 1; i < N; i++)
for (int j = 1; j < i + 1 && j < N; j++)
dp[i][j] = mat[i][j] +
Math.max(dp[i-1][j-1],
dp[i-1][j]);
// find the max weight path sum to reach
// the last row
int result = 0;
for (int i = 0; i < N; i++)
if (result < dp[N-1][i])
result = dp[N-1][i];
// return maximum weight path sum
return result;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int mat[][] = { { 4, 1 ,5 ,6 , 1 },
{ 2 ,9 ,2 ,11 ,10 },
{ 15,1 ,3 ,15, 2 },
{ 16, 92, 41,4,3},
{ 8, 142, 6, 4, 8 }
};
int N = 5;
System.out.println("Maximum Path Sum : "+
maxCost(mat, N));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
1840
Chapter 251. Maximum weight path ending at any element of last row in a matrix
C#
1841
Chapter 251. Maximum weight path ending at any element of last row in a matrix
// row in a matrix
using System;
class GFG {
/* Function which return the
maximum weight path sum */
public static int maxCost(int [,] mat, int N)
{
// create 2D matrix to store the
// sum of the path
int [,] dp = new int[N,N];
dp[0,0] = mat[0,0];
// Initialize first column of total
// weight array (dp[i to N][0])
for (int i = 1; i < N; i++)
dp[i,0] = mat[i,0] + dp[i-1,0];
// Calculate rest path sum of weight matrix
for (int i = 1; i < N; i++)
for (int j = 1; j < i + 1 && j < N; j++)
dp[i,j] = mat[i,j] +
Math.Max(dp[i-1,j-1], dp[i-1,j]);
// find the max weight path sum to reach
// the last row
int result = 0;
for (int i = 0; i < N; i++)
if (result < dp[N-1,i])
result = dp[N-1,i];
// return maximum weight path sum
return result;
}
/* Driver program to test above function */
public static void Main()
{
int [,] mat = { { 4, 1 ,5 ,6 , 1 },
{ 2 ,9 ,2 ,11 ,10 },
{ 15,1 ,3 ,15, 2 },
{ 16, 92, 41,4,3},
{ 8, 142, 6, 4, 8 }
};
1842
Chapter 251. Maximum weight path ending at any element of last row in a matrix
int N = 5;
Console.Write("Maximum Path Sum : "
+ maxCost(mat, N));
}
}
// This code is contributed by KRV.
Output:
Source
https://www.geeksforgeeks.org/maximum-weight-path-ending-element-last-row-matrix/
1843
Chapter 252
Maximum weight
transformation of a given string
Examples :
1844
Chapter 252. Maximum weight transformation of a given string
Output: 5
Transformations are "ABB", "ABA", "AAB", "AAA", "BBB",
"BBA", "BAB" and "BAA"
Maximum weight is of original string 4+1 (One Pair + 1
character)
If (n == 1)
maxWeight(str[0..n-1]) = 1
If we draw the complete recursion tree, we can observer that many subproblems are solved
again and again. Since same suproblems are called again, this problem has Overlapping
Subprolems property. So min square sum problem has both properties (see thisand this) of
a dynamic programming problem. Like other typical Dynamic Programming(DP) problems.
Below is a memoization based solution. A lookup table is used to see if a problem is already
computed.
C++
1845
Chapter 252. Maximum weight transformation of a given string
1846
Chapter 252. Maximum weight transformation of a given string
C#
1847
Chapter 252. Maximum weight transformation of a given string
Output:
Source
https://www.geeksforgeeks.org/maximum-weight-transformation-of-a-given-string/
1848
Chapter 253
1. Tabulation: Bottom Up
2. Memoization: Top Down
One of the easier approaches to solve most of the problems in DP is to write the recursive
code at first and then write the Bottom-up Tabulation Method or Top-down Memoization
of the recursive function. The steps to write the DP solution of Top-down approach to any
problem is to:
1-D Memoization
The first step will be to write the recursive code. In the program below, a program related
to recursion where only one parameter changes its value has been shown. Since only one
parameter is non-constant, this method is known as 1-D memoization. E.g., the Fibonacci
series problem to find the N-th term in the Fibonacci series. The recursive approach has
been discussed over here.
Given below is the recursive code to find the N-th term:
C++
1849
Chapter 253. Memoization (1D, 2D and 3D)
Java
1850
Chapter 253. Memoization (1D, 2D and 3D)
}
}
// This code is contributed
// by ajit
C#
// C# program to find
// the Nth term of
// Fibonacci series
using System;
class GFG
{
// Fibonacci Series
// using Recursion
static int fib(int n)
{
// Base case
if (n <= 1)
return n;
// recursive calls
return fib(n - 1) +
fib(n - 2);
}
// Driver Code
static public void Main ()
{
int n = 6;
Console.WriteLine(fib(n));
}
}
// This code is contributed
// by akt_mit
PHP
<?php
// PHP program to find
// the Nth term of
// Fibonacci series
// using Recursion
1851
Chapter 253. Memoization (1D, 2D and 3D)
function fib($n)
{
// Base case
if ($n <= 1)
return $n;
// recursive calls
return fib($n - 1) +
fib($n - 2);
}
// Driver Code
$n = 6;
echo fib($n);
// This code is contributed
// by ajit
?>
Output:
A common observation is that this implementation does a lot of repeated work (see the
following recursion tree). So this will consume a lot of time for finding the N-th Fibonacci
number if done.
fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/ \
fib(1) fib(0)
In the above tree fib(3), fib(2), fib(1), fib(0) all are called more then once.
1852
Chapter 253. Memoization (1D, 2D and 3D)
the value of fib(x) in an array term at index x and return term[x]. By memoizing
the return value of fib(x) at index x of an array, reduce the number of recursive calls at
the next step when fib(x) has already been called. So without doing further recursive calls
to compute the value of fib(x), return term[x] when fib(x) has already been computed
previously to avoid a lot of repeated work as shown in the tree.
Given below is the memoized recursive code to find the N-th term.
C++
1853
Chapter 253. Memoization (1D, 2D and 3D)
Java
1854
Chapter 253. Memoization (1D, 2D and 3D)
System.out.println(fib(n));
}
}
// This code is contributed by ajit
Output:
If the recursive code has been written once, then memoization is just modifying the recursive
program and storing the return values to avoid repetitive calls of functions which have been
computed previously.
2-D Memoization
In the above program, the recursive function had only one argument whose value was
not constant after every function call. Below, an implementation where the recursive
program has two non-constant arguments has been shown.
For e.g., Program to solve the standard Dynamic Problem LCS problem when two strings are
given. The general recursive solution of the problem is to generate all subsequences of both
given sequences and find the longest matching subsequence. Total possible combinations
will be 2n . Hence recursive solution will take O(2n ). The approach to write the recursive
solution has been discussed here.
Given below is the recursive solution to the LCS problem:
C++
1855
Chapter 253. Memoization (1D, 2D and 3D)
Output:
Length of LCS is 4n
Output:
Length of LCS is 4
Considering the above implementation, the following is a partial recursion tree for input
strings “AXYT” and “AYZX”
lcs("AXYT", "AYZX")
/ \
lcs("AXY", "AYZX") lcs("AXYT", "AYZ")
/ \ / \
lcs("AX", "AYZX") lcs("AXY", "AYZ") lcs("AXY", "AYZ") lcs("AXYT", "AY")
In the above partial recursion tree, lcs(“AXY”, “AYZ”) is being solved twice. On
drawing the complete recursion tree, it has been observed that there are many subproblems
which are solved again and again. So this problem has Overlapping Substructure property
and recomputation of same subproblems can be avoided by either using Memoization or
Tabulation. The tabulation method has been discussed here.
A common point of observation to use memoization in the recursive code will be the two
non-constant arguments M and N in every function call. The function has 4 arguments,
but 2 arguments are constant which do not affect the Memoization. The repetitive calls occur
1856
Chapter 253. Memoization (1D, 2D and 3D)
for N and M which have been called previously. So use a 2-D array to store the computed
lcs(m, n) value at arr[m-1][n-1] as the string index starts from 0. Whenever the function
with the same argument m and n are called again, we do not perform any further recursive
call and return arr[m-1][n-1] as the previous computation of the lcs(m, n) has already been
stored in arr[m-1][n-1], hence reducing the recursive calls that happen more then once.
Below is the implementation of the Memoization approach of the recursive code.
C++
1857
Chapter 253. Memoization (1D, 2D and 3D)
Output:
Length of LCS is 4
3-D Memoization
In the above program, the recursive function had only two arguments whose value were not
constant after every function call. Below, an implementation where the recursive program
has three non-constant arguments is done.
For e.g., Program to solve the standard Dynamic Problem LCS problem for three strings.
The general recursive solution of the problem is to generate all subsequences of both given
sequences and find the longest matching subsequence. Total possible combinations will be
3n . Hence recursive solution will take O(3n ).
Given below is the recursive solution to the LCS problem:
C++
1858
Chapter 253. Memoization (1D, 2D and 3D)
if (m == 0 || n == 0 || o == 0)
return 0;
// if equal, then check for next combination
if (X[m - 1] == Y[n - 1] and Y[n - 1] == Z[o - 1]) {
// recursive call
return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1);
}
else {
// return the maximum of the three other
// possible states in recursion
return max(lcs(X, Y, Z, m, n - 1, o),
max(lcs(X, Y, Z, m - 1, n, o),
lcs(X, Y, Z, m, n, o - 1)));
}
}
// Utility function to get max of 2 integers
int max(int a, int b)
{
return (a > b) ? a : b;
}
// Driver Code
int main()
{
char X[] = "geeks";
char Y[] = "geeksfor";
char Z[] = "geeksforge";
int m = strlen(X);
int n = strlen(Y);
int o = strlen(Z);
printf("Length of LCS is %d", lcs(X, Y, Z, m, n, o));
return 0;
}
Output:
Length of LCS is 5
The tabulation method has been shown here. On drawing the recursion tree completely, it
has been noticed that there are many overlapping sub-problems which are been calculated
1859
Chapter 253. Memoization (1D, 2D and 3D)
multiple times. Since the function parameter has three non-constant parameters, hence a
3-D array will be used to memoize the value that was returned when lcs(x, y, z, m, n,
o) for any value of m, n and o was called so that if lcs(x, y, z, m, n, o) is again called
for the same value of m, n and o then the function will return the already stored value as
it has been computed previously in the recursive call. arr[m][n][o] stores the value returned
by the lcs(x, y, z, m, n, o) function call. The only modification that needs to be done in
the recursive program is to store the return value of (m, n, o) state of the recursive function.
The rest remains the same in the above recursive program.
Below is the implementation of the Memoization approach of the recursive code:
C++
1860
Chapter 253. Memoization (1D, 2D and 3D)
lcs(X, Y, Z, m, n, o - 1)));
return arr[m - 1][n - 1][o - 1];
}
}
// Utility function to get max of 2 integers
int max(int a, int b)
{
return (a > b) ? a : b;
}
// Driver Code
int main()
{
memset(arr, -1, sizeof(arr));
char X[] = "geeks";
char Y[] = "geeksfor";
char Z[] = "geeksforgeeks";
int m = strlen(X);
int n = strlen(Y);
int o = strlen(Z);
printf("Length of LCS is %d", lcs(X, Y, Z, m, n, o));
return 0;
}
Output:
Length of LCS is 5
Note: The array used to Memoize is initialized to some value (say -1) before the function
call to mark if the function with the same parameters has been previously called or not.
Improved By : jit_t
Source
https://www.geeksforgeeks.org/memoization-1d-2d-and-3d/
1861
Chapter 254
Minimal moves to form a string by adding characters or appending string itself - Geeks-
forGeeks
Given a string S, we need to write a program to check if it is possible to construct the given
string S by performing any of the below operations any number of times. In each step, we
can:
The above steps can be applied any number of times. We need to write a program to print
the minimum steps required to form the string.
Examples:
Input : aaaaaaaa
Output : 4
Explanation: move 1: add 'a' to form "a"
move 2: add 'a' to form "aa"
move 3: append "aa" to form "aaaa"
move 4: append "aaaa" to form "aaaaaaaa"
Input: aaaaaa
Output: 4
Explanation: move 1: add 'a' to form "a"
move 2: add 'a' to form "aa"
1862
Chapter 254. Minimal moves to form a string by adding characters or appending string
itself
Input: abcabca
Output: 5
The idea to solve this problem is to use Dynamic Programming to count the minimum
number of moves. Create an array named dp of size n, where n is the length of the input
string. dp[i] stores the minimum number of moves that are required to make substring (0…i).
According to the question there are two moves that are possible:
Source
https://www.geeksforgeeks.org/minimal-moves-form-string-adding-characters-appending-string/
1863
Chapter 255
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
1864
Chapter 255. Minimum Cost Path with Left, Right, Bottom and Up moves allowed
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
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.
1865
Chapter 255. Minimum Cost Path with Left, Right, Bottom and Up moves allowed
{
int dis[row][col];
// initializing distance array by INT_MAX
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
dis[i][j] = INT_MAX;
// direction arrays for simplification of getting
// neighbour
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
set<cell> st;
// insert (0, 0) cell with 0 distance
st.insert(cell(0, 0, 0));
// initialize distance of (0, 0) with its grid value
dis[0][0] = grid[0][0];
// loop for standard dijkstra's algorithm
while (!st.empty())
{
// get the cell with minimum distance and delete
// it from the set
cell k = *st.begin();
st.erase(st.begin());
// looping through all neighbours
for (int i = 0; i < 4; i++)
{
int x = k.x + dx[i];
int y = k.y + dy[i];
// if not inside boundry, ignore them
if (!isInsideGrid(x, y))
continue;
// If distance from current cell is smaller, then
// update distance of neighbour cell
if (dis[x][y] > dis[k.x][k.y] + grid[x][y])
{
// If cell is already there in set, then
// remove its previous entry
if (dis[x][y] != INT_MAX)
st.erase(st.find(cell(x, y, dis[x][y])));
1866
Chapter 255. 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/
1867
Chapter 256
Two triangulations of the same convex pentagon. The triangulation on the left has a cost
of 8 + 2√2 + 2√5 (approximately 15.30), the one on the right has a cost of 4 + 2√2 + 4√5
(approximately 15.77).
This problem has recursive substructure. The idea is to divide the polygon into three parts:
a single triangle, the sub-polygon to the left, and the sub-polygon to the right. We try all
possible divisions like this and find the one that minimizes the cost of the triangle plus the
cost of the triangulation of the two sub-polygons.
1868
Chapter 256. Minimum Cost Polygon Triangulation
minCost(i, j) = 0
Else
minCost(i, j) = Min { minCost(i, k) + minCost(k, j) + cost(i, k, j) }
Here k varies from 'i+1' to 'j-1'
1869
Chapter 256. Minimum Cost Polygon Triangulation
Output:
15.3006
The above problem is similar to Matrix Chain Multiplication. The following is recursion
tree for mTC(points[], 0, 4).
1870
Chapter 256. Minimum Cost Polygon Triangulation
It can be easily seen in the above recursion tree that the problem has many overlapping sub-
problems. Since the problem has both properties: Optimal Substructure and Overlapping
Subproblems, it can be efficiently solved using dynamic programming.
Following is C++ implementation of dynamic programming solution.
1871
Chapter 256. Minimum Cost Polygon Triangulation
Output:
15.3006
1872
Chapter 256. Minimum Cost Polygon Triangulation
Sources:
http://www.cs.utexas.edu/users/djimenez/utsa/cs3343/lecture12.html
http://www.cs.utoronto.ca/~heap/Courses/270F02/A4/chains/node2.html
Source
https://www.geeksforgeeks.org/minimum-cost-polygon-triangulation/
1873
Chapter 257
This problem is a variation of Longest Common Subsequence ( LCS ). The idea is simple,
we first find the length of longest common subsequence of strings X and Y. Now subtracting
len_LCS with lengths of individual strings gives us number of characters to be removed to
make them identical.
1874
Chapter 257. Minimum Cost To Make Two Strings Identical
C++
1875
Chapter 257. Minimum Cost To Make Two Strings Identical
/* L[m][n] contains length of LCS for X[0..n-1] and
Y[0..m-1] */
return L[m][n];
}
// Returns cost of making X[] and Y[] identical. costX is
// cost of removing a character from X[] and costY is cost
// of removing a character from Y[]/
int findMinCost(char X[], char Y[], int costX, int costY)
{
// Find LCS of X[] and Y[]
int m = strlen(X), n = strlen(Y);
int len_LCS = lcs(X, Y, m, n);
// Cost of making two strings identical is SUM of
// following two
// 1) Cost of removing extra characters
// from first string
// 2) Cost of removing extra characters from
// second string
return costX * (m - len_LCS) +
costY * (n - len_LCS);
}
/* Driver program to test above function */
int main()
{
char X[] = "ef";
char Y[] = "gh";
cout << "Minimum Cost to make two strings "
<< " identical is = " << findMinCost(X, Y, 10, 20);
return 0;
}
Java
1876
Chapter 257. Minimum Cost To Make Two Strings Identical
1877
Chapter 257. Minimum Cost To Make Two Strings Identical
String Y = "gh";
System.out.println( "Minimum Cost to make two strings "
+ " identical is = "
+ findMinCost(X, Y, 10, 20));
}
}
// This code is contributed by vt_m
C#
1878
Chapter 257. Minimum Cost To Make Two Strings Identical
Output:
Source
https://www.geeksforgeeks.org/minimum-cost-make-two-strings-identical/
1879
Chapter 258
1880
Chapter 258. Minimum Initial Points to Reach Destination
At the first look, this problem looks similar Max/Min Cost Path, but maximum overall
points gained will not guarantee the minimum initial points. Also, it is compulsory in
the current problem that the points never drops to zero or below. For instance, Suppose
following two paths exists from source to destination cell.
We can solve this problem through bottom-up table filling dynamic programing technique.
• To begin with, we should maintain a 2D array dp of the same size as the grid, where
dp[i][j] represents the minimum points that guarantees the continuation of the journey
to destination before entering the cell (i, j). It’s but obvious that dp[0][0] is our final
solution. Hence, for this problem, we need to fill the table from the bottom right
corner to left top.
• Now, let us decide minimum points needed to leave cell (i, j) (remember we are
moving from bottom to up). There are only two paths to choose: (i+1, j) and (i,
j+1). Of course we will choose the cell that the player can finish the rest of his
journey with a smaller initial points. Therefore we have: min_Points_on_exit =
min(dp[i+1][j], dp[i][j+1])
Now we know how to compute min_Points_on_exit, but we need to fill the table dp[][] to
get the solution in dp[0][0].
How to compute dp[i][j]?
The value of dp[i][j] can be written as below.
• If points[i][j] == 0, then nothing is gained in this cell; the player can leave the cell
with the same points as he enters the room with, i.e. dp[i][j] = min_Points_on_exit.
• If dp[i][j] < 0, then the player must have points greater than min_Points_on_exit be-
fore entering (i, j) in order to compensate for the points lost in this cell. The minimum
amount of compensation is ” – points[i][j] ”, so we have dp[i][j] = min_Points_on_exit
– points[i][j].
• If dp[i][j] > 0, then the player could enter (i, j) with points as little as
min_Points_on_exit – points[i][j]. since he could gain “points[i][j]” points in
this cell. However, the value of min_Points_on_exit – points[i][j] might drop to 0 or
below in this situation. When this happens, we must clip the value to 1 in order to
make sure dp[i][j] stays positive:
dp[i][j] = max(min_Points_on_exit – points[i][j], 1).
C++
1881
Chapter 258. Minimum Initial Points to Reach Destination
1882
Chapter 258. Minimum Initial Points to Reach Destination
<< minInitialPoints(points);
return 0;
}
Java
class min_steps
{
static int minInitialPoints(int points[][],int R,int C)
{
// dp[i][j] represents the minimum initial points player
// should have so that when starts with cell(i, j) successfully
// reaches the destination cell(m-1, n-1)
int dp[][] = new int[R][C];
int m = R, n = C;
// Base case
dp[m-1][n-1] = points[m-1][n-1] > 0? 1:
Math.abs(points[m-1][n-1]) + 1;
// Fill last row and last column as base to fill
// entire table
for (int i = m-2; i >= 0; i--)
dp[i][n-1] = Math.max(dp[i+1][n-1] - points[i][n-1], 1);
for (int j = n-2; j >= 0; j--)
dp[m-1][j] = Math.max(dp[m-1][j+1] - points[m-1][j], 1);
// fill the table in bottom-up fashion
for (int i=m-2; i>=0; i--)
{
for (int j=n-2; j>=0; j--)
{
int min_points_on_exit = Math.min(dp[i+1][j], dp[i][j+1]);
dp[i][j] = Math.max(min_points_on_exit - points[i][j], 1);
}
}
return dp[0][0];
}
/* Driver program to test above function */
public static void main (String args[])
{
int points[][] = { {-2,-3,3},
{-5,-10,1},
{10,30,-5}
};
int R = 3,C = 3;
1883
Chapter 258. Minimum Initial Points to Reach Destination
C#
1884
Chapter 258. Minimum Initial Points to Reach Destination
dp[i, j] = Math.Max(min_points_on_exit -
points[i, j], 1);
}
}
return dp[0, 0];
}
// Driver Code
public static void Main ()
{
int [,]points = {{-2,-3,3},
{-5,-10,1},
{10,30,-5}};
int R = 3,C = 3;
Console.Write("Minimum Initial Points Required: "+
minInitialPoints(points, R, C));
}
}
// This code is contributed by nitin mittal.
Output:
This article is contributed by Gaurav Ahirwar. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal, PrathamKohli
Source
https://www.geeksforgeeks.org/minimum-positive-points-to-reach-destination/
1885
Chapter 259
Let us consider a 3-D array arr[2][2][2] represented by a cuboid having values as:
1886
Chapter 259. Minimum Sum Path In 3-D Array
This problem is similar to Min cost path. and can be solved using Dynamic Programming/
tSum[0][0][0] = arr[0][0][0];
1887
Chapter 259. Minimum Sum Path In 3-D Array
return tSum[l-1][m-1][n-1];
C++
1888
Chapter 259. Minimum Sum Path In 3-D Array
/* Initialize first row- First column of
tSum array */
for (i = 1; i < l; i++)
for (j = 1; j < m; j++)
tSum[i][j][0] = min(tSum[i-1][j][0],
tSum[i][j-1][0],
INT_MAX)
+ arr[i][j][0];
/* Initialize first row- First width of
tSum array */
for (i = 1; i < l; i++)
for (k = 1; k < n; k++)
tSum[i][0][k] = min(tSum[i-1][0][k],
tSum[i][0][k-1],
INT_MAX)
+ arr[i][0][k];
/* Initialize first width- First column of
tSum array */
for (k = 1; k < n; k++)
for (j = 1; j < m; j++)
tSum[0][j][k] = min(tSum[0][j][k-1],
tSum[0][j-1][k],
INT_MAX)
+ arr[0][j][k];
/* Construct rest of the tSum array */
for (i = 1; i < l; i++)
for (j = 1; j < m; j++)
for (k = 1; k < n; k++)
tSum[i][j][k] = min(tSum[i-1][j][k],
tSum[i][j-1][k],
tSum[i][j][k-1])
+ arr[i][j][k];
return tSum[l-1][m-1][n-1];
}
// Driver program
int main()
{
int arr[l][m][n] = { { {1, 2, 4}, {3, 4, 5}, {5, 2, 1}},
{ {4, 8, 3}, {5, 2, 1}, {3, 4, 2}},
1889
Chapter 259. Minimum Sum Path In 3-D Array
Java
1890
Chapter 259. Minimum Sum Path In 3-D Array
1891
Chapter 259. Minimum Sum Path In 3-D Array
}
}
// This code is contributed by vt_m
C#
1892
Chapter 259. Minimum Sum Path In 3-D Array
1893
Chapter 259. Minimum Sum Path In 3-D Array
return tSum[l-1,m-1,n-1];
}
// Driver Code
static public void Main ()
{
int [, , ]arr= {{{1, 2, 4}, {3, 4, 5}, {5, 2, 1}},
{{4, 8, 3}, {5, 2, 1}, {3, 4, 2}},
{{2, 4, 1}, {3, 1, 4}, {6, 3, 8}}};
Console.WriteLine(minPathSum(arr));
}
}
// This code is contributed by ajit
Output :
20
Source
https://www.geeksforgeeks.org/minimum-sum-path-3-d-array/
1894
Chapter 260
Input :
2
3 7
8 5 6
6 1 9 3
Output : 11
Explanation : 2 + 3 + 5 + 1 = 11
Input :
3
6 4
5 2 7
9 1 8 6
Output : 10
Explanation : 3 + 4 + 2 + 1 = 10
Naive Approach : Going through the Naive approach by traversing every possible path.
But, this is costly. So, use Dynamic Programming here in order to reduce the time com-
plexity.
There are two ways to reach the solution :
1. Memoization – Starting from the top node, traverse recursively with each node, till the
1895
Chapter 260. Minimum Sum Path in a Triangle
pathsum of that node is calculated. And then store the result in an array. But this will
take O(N^2) space to maintain the array.
2. Bottom up – Start from the nodes on the bottom row; the min pathsum for these nodes
are the values of the nodes themselves. And after that, minimum pathsum at the ith node
of kth row would be the minimum of the pathsum of its two children + the node’s value,
i.e.:
OR
Simply set memo as a 1D array, and update it
this will be space efficient also :
For the row k :
C++
1896
Chapter 260. Minimum Sum Path in a Triangle
memo[j + 1]);
// return the top element
return memo[0];
}
/* Driver program to test above functions */
int main()
{
vector<vector<int> > A{ { 2 },
{ 3, 9 },
{ 1, 6, 7 } };
cout << minSumPath(A);
return 0;
}
Java
1897
Chapter 260. Minimum Sum Path in a Triangle
Python 3
1898
Chapter 260. Minimum Sum Path in a Triangle
C#
1899
Chapter 260. Minimum Sum Path in a Triangle
// return the top element
return memo[0];
}
// Driver Code
public static void Main()
{
List<List<int>> A = new List<List<int>>();
A.Add(new List<int> {2});
A.Add(new List<int> {3, 9});
A.Add(new List<int> {1, 6, 7});
Console.WriteLine(minSumPath(ref A));
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
PHP
<?php
// PHP program for Dynamic
// Programming implementation of
// Min Sum Path in a Triangle
// Util function to find
// minimum sum for a path
function minSumPath(&$A)
{
// For storing the result
// in a 1-D array, and
// simultaneously updating
// the result.
$memo = array();
for ($i = 0; $i < count($A); $i++)
$memo[$i] = 0;
$n = count($A) - 1;
// For the bottom row
for ($i = 0;
$i < count($A[$n]); $i++)
$memo[$i] = $A[$n][$i];
// Calculation of
// the remaining rows,
// in bottom up manner.
1900
Chapter 260. Minimum Sum Path in a Triangle
Output:
Source
https://www.geeksforgeeks.org/minimum-sum-path-triangle/
1901
Chapter 261
We can solve this problem by dynamic programming method, we can see that this problem
is similar to matrix chain multiplication, here we are trying different parenthesization to
maximize and minimize expression value instead of number of matrix multiplication.
In below code first we have separated the operators and numbers from given expression then
two 2D arrays are taken for storing the intermediate result which are updated similar to
matrix chain multiplication and different parenthesization are tried among the numbers but
according to operators occurring in between them. At the end last cell of first row will store
the final result in both the 2D arrays.
1902
Chapter 261. Minimum and Maximum values of an expression with * and +
// is operator or not
bool isOperator(char op)
{
return (op == '+' || op == '*');
}
// method prints minimum and maximum value
// obtainable from an expression
void printMinAndMaxValueOfExp(string exp)
{
vector<int> num;
vector<char> opr;
string tmp = "";
// store operator and numbers in different vectors
for (int i = 0; i < exp.length(); i++)
{
if (isOperator(exp[i]))
{
opr.push_back(exp[i]);
num.push_back(atoi(tmp.c_str()));
tmp = "";
}
else
{
tmp += exp[i];
}
}
// storing last number in vector
num.push_back(atoi(tmp.c_str()));
int len = num.size();
int minVal[len][len];
int maxVal[len][len];
// initializing minval and maxval 2D array
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len; j++)
{
minVal[i][j] = INT_MAX;
maxVal[i][j] = 0;
// initializing main diagonal by num values
if (i == j)
minVal[i][j] = maxVal[i][j] = num[i];
}
}
1903
Chapter 261. Minimum and Maximum values of an expression with * and +
// looping similar to matrix chain multiplication
// and updating both 2D arrays
for (int L = 2; L <= len; L++)
{
for (int i = 0; i < len - L + 1; i++)
{
int j = i + L - 1;
for (int k = i; k < j; k++)
{
int minTmp = 0, maxTmp = 0;
// if current operator is '+', updating tmp
// variable by addition
if(opr[k] == '+')
{
minTmp = minVal[i][k] + minVal[k + 1][j];
maxTmp = maxVal[i][k] + maxVal[k + 1][j];
}
// if current operator is '*', updating tmp
// variable by multiplication
else if(opr[k] == '*')
{
minTmp = minVal[i][k] * minVal[k + 1][j];
maxTmp = maxVal[i][k] * maxVal[k + 1][j];
}
// updating array values by tmp variables
if (minTmp < minVal[i][j])
minVal[i][j] = minTmp;
if (maxTmp > maxVal[i][j])
maxVal[i][j] = maxTmp;
}
}
}
// last element of first row will store the result
cout << "Minimum value : " << minVal[0][len - 1]
<< ", Maximum value : " << maxVal[0][len - 1];
}
// Driver code to test above methods
int main()
{
string expression = "1+2*3+4*5";
printMinAndMaxValueOfExp(expression);
return 0;
1904
Chapter 261. Minimum and Maximum values of an expression with * and +
Output:
Source
https://www.geeksforgeeks.org/minimum-maximum-values-expression/
1905
Chapter 262
Minimum cells required to reach destination with jumps equal to cell values - GeeksforGeeks
Given a m x n matrix mat[][] containing positive integers. The problem is to reach to the
cell (m-1, n-1) from the cell (0, 0) by following the given constraints. From a cell (i, j) one
can move ‘exactly’ a distance of ‘mat[i][j]’ to the right (in the same row) or to below (in the
same column) only if the movement takes to a cell within matrix boundaries.
For example: Given mat[1][1] = 4, then one can move to cells mat[1][5] and mat[5][1] only if
these cells exists in the matrix. Following the constraints check whether one can reach cell
(m-1, n-1) from (0, 0). 1If one can reach then print the minimum number of cells required
to be covered during the movement else print “-1”.
Examples:
1906
Chapter 262. Minimum cells required to reach destination with jumps equal to cell values
C++
1907
Chapter 262. Minimum cells required to reach destination with jumps equal to cell values
Java
1908
Chapter 262. Minimum cells required to reach destination with jumps equal to cell values
1909
Chapter 262. Minimum cells required to reach destination with jumps equal to cell values
C#
1910
Chapter 262. Minimum cells required to reach destination with jumps equal to cell values
1911
Chapter 262. Minimum cells required to reach destination with jumps equal to cell values
PHP
<?php
// PHP implementation to count
// minimum cells required to be
// covered to reach destination
// function to count minimum
// cells required to be
// covered to reach destination
function minCells( $mat, $m, $n)
{
// to store min cells
// required to be
// covered to reach
// a particular cell
$dp =array(array());
// initially no cells
// can be reached
for($i = 0; $i < $m; $i++)
for($j = 0; $j < $n; $j++)
$dp[$i][$j] = PHP_INT_MAX;
// base case
$dp[0][0] = 1;
// building up the dp[][] matrix
for($i = 0; $i < $m; $i++)
{
for($j = 0; $j < $n; $j++)
{
// dp[i][j] != INT_MAX
// denotes that cell (i, j)
// can be reached from cell
// (0, 0) and the other half
// of the condition finds the
// cell on the right that can
// be reached from (i, j)
if ($dp[$i][$j] != PHP_INT_MAX and
1912
Chapter 262. Minimum cells required to reach destination with jumps equal to cell values
Output:
1913
Chapter 262. Minimum cells required to reach destination with jumps equal to cell values
Source
https://www.geeksforgeeks.org/minimum-cells-required-reach-destination-jumps-equal-cell-values/
1914
Chapter 263
1915
Chapter 263. Minimum cost to fill given weight in a bag
This problem is can be reduced to 0-1 Knapsack Problem. So in cost array, we first ignore
those packets which are not available i.e; cost is -1 and then traverse the cost array and
create two array val[] for storing cost of ‘i’ kg packet of orange and wt[] for storing weight
of corresponding packet. Suppose cost[i] = 50 so weight of packet will be i and cost will be
50.
Algorithm :
C++
1916
Chapter 263. Minimum cost to fill given weight in a bag
1917
Chapter 263. Minimum cost to fill given weight in a bag
{
int cost[] = {1, 2, 3, 4, 5}, W = 5;
int n = sizeof(cost)/sizeof(cost[0]);
cout << MinimumCost(cost, n, W);
return 0;
}
Java
1918
Chapter 263. Minimum cost to fill given weight in a bag
min_cost[0][i] = Integer.MAX_VALUE;
// fill 0'th column with 0
for (int i = 1; i <= n; i++)
min_cost[i][0] = 0;
// now check for each weight one by one and
// fill the matrix according to the condition
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= W; j++)
{
// wt[i-1]>j means capacity of bag is
// less then weight of item
if (wt.get(i-1) > j)
min_cost[i][j] = min_cost[i-1][j];
// here we check we get minimum cost
// either by including it or excluding
// it
else
min_cost[i][j] = Math.min(min_cost[i-1][j],
min_cost[i][j-wt.get(i-1)] +
val.get(i-1));
}
}
// exactly weight W can not be made by
// given weights
return (min_cost[n][W] == Integer.MAX_VALUE)? -1:
min_cost[n][W];
}
/* Driver program to test above function */
public static void main(String[] args)
{
int cost[] = {1, 2, 3, 4, 5}, W = 5;
int n = cost.length;
System.out.println(MinimumCost(cost, n, W));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python 3
1919
Chapter 263. Minimum cost to fill given weight in a bag
INF = 1000000
# cost[] initial cost array including unavailable packet
# W capacity of bag
def MinimumCost(cost, n, W):
# val[] and wt[] arrays
# val[] array to store cost of 'i' kg packet of orange
# wt[] array weight of packet of orange
val = list()
wt= list()
# traverse the original cost[] array and skip
# unavailable packets and make val[] and wt[]
# array. size variable tells the available number
# of distinct weighted packets.
size = 0
for i in range(n):
if (cost[i] != -1):
val.append(cost[i])
wt.append(i+1)
size += 1
n = size
min_cost = [[0 for i in range(W+1)] for j in range(n+1)]
# fill 0th row with infinity
for i in range(W+1):
min_cost[0][i] = INF
# fill 0th column with 0
for i in range(1, n+1):
min_cost[i][0] = 0
# now check for each weight one by one and fill the
# matrix according to the condition
for i in range(1, n+1):
for j in range(1, W+1):
# wt[i-1]>j means capacity of bag is
# less than weight of item
if (wt[i-1] > j):
min_cost[i][j] = min_cost[i-1][j]
# here we check we get minimum cost either
# by including it or excluding it
else:
min_cost[i][j] = min(min_cost[i-1][j],
1920
Chapter 263. Minimum cost to fill given weight in a bag
min_cost[i][j-wt[i-1]] + val[i-1])
# exactly weight W can not be made by given weights
if(min_cost[n][W] == INF):
return -1
else:
return min_cost[n][W]
# Driver program to run the test case
cost = [1, 2, 3, 4, 5]
W = 5
n = len(cost)
print(MinimumCost(cost, n, W))
# This code is contributed by Soumen Ghosh.
Output:
Source
https://www.geeksforgeeks.org/minimum-cost-to-fill-given-weight-in-a-bag/
1921
Chapter 264
Input : X = "abble",
Y = "pie",
k = 2
Output : 25
The problem can be solved by slight change in Dynamic Programming problem of Longest
Increasing Subsequence. Instead of two states, we maintain three states.
Note, that if k > min(n, m) then it’s impossible to attain LCS of atleast k length, else it’s
always possible.
Let dp[i][j][p] stores the minimum cost to achieve LCS of length p in x[0…i] and y[0….j].
With base step as dp[i][j][0] = 0 because we can achieve LCS of 0 legth without any cost
and for i < 0 or j 0 in such case).
Else there are 3 cases:
1. Convert x[i] to y[j].
2. Skip ith character from x.
3. Skip jth character from y.
1922
Chapter 264. Minimum cost to make Longest Common Subsequence of length k
If we convert x[i] to y[j], then cost = f(x[i]) XOR f(y[j]) will be added and LCS will decrease
by 1. f(x) will return the character value of x.
Note that the minimum cost to convert a charcater ‘a’ to any character ‘c’ is always f(a)
XOR f(c) because f(a) XOR f(c) <= (f(a) XOR f(b) + f(b) XOR f(c)) for all a, b, c.
If you skip ith character from x then i will be decreased by 1, no cost will be added and LCS
will remain the same.
If you skip jth character from x then j will be decreased by 1, no cost will be added and LCS
will remain the same.
Therefore,
#include <bits/stdc++.h>
using namespace std;
const int N = 30;
// Return Minimum cost to make LCS of length k
int solve(char X[], char Y[], int l, int r,
int k, int dp[][N][N])
{
// If k is 0.
if (!k)
return 0;
// If length become less than 0, return
// big number.
if (l < 0 | r < 0)
return 1e9;
// If state already calculated.
if (dp[l][r][k] != -1)
return dp[l][r][k];
// Finding the cost
int cost = (X[l] - 'a') ^ (Y[r] - 'a');
// Finding minimum cost and saving the state value
return dp[l][r][k] = min({cost +
solve(X, Y, l - 1, r - 1, k - 1, dp),
solve(X, Y, l - 1, r, k, dp),
1923
Chapter 264. Minimum cost to make Longest Common Subsequence of length k
solve(X, Y, l, r - 1, k, dp)});
}
// Driven Program
int main()
{
char X[] = "abble";
char Y[] = "pie";
int n = strlen(X);
int m = strlen(Y);
int k = 2;
int dp[N][N][N];
memset(dp, -1, sizeof dp);
int ans = solve(X, Y, n - 1, m - 1, k, dp);
cout << (ans == 1e9 ? -1 : ans) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/minimum-cost-make-longest-common-subsequence-length-k/
1924
Chapter 265
Minimum cost to make two strings identical by deleting the digits - GeeksforGeeks
Given two strings X and Y consisting of only digits ‘0’ to ‘9’. Find minimum cost required
to make the given two strings identical. Only operation allowed is to delete characters from
any of the string. The cost of operation of deleting the digit ‘d’ is d units.
Input: X = 3198, Y = 98
Output: 4
This problem is a variation of Longest Common Subsequence( LCS ) and this one. The idea
is simple, instead of finding the length of longest common subsequence, find the maximum
cost by adding identical characters from both the string.
Now to find the minimum cost, subtract the above result from total cost of both strings i.e.,
1925
Chapter 265. Minimum cost to make two strings identical by deleting the digits
C++
1926
Chapter 265. Minimum cost to make two strings identical by deleting the digits
Java
1927
Chapter 265. Minimum cost to make two strings identical by deleting the digits
1928
Chapter 265. Minimum cost to make two strings identical by deleting the digits
System.out.println("Minimum Cost to make two strings"+
" identical is = " +findMinCost(X, Y));
}
}
// This code is contributed by Prerna Saini
C#
1929
Chapter 265. Minimum cost to make two strings identical by deleting the digits
// Returns cost of making X[] and Y[] identical
static int findMinCost( string X, string Y)
{
// Find LCS of X[] and Y[]
int m = X.Length, n = Y.Length;
// Initialize the cost variable
int cost = 0;
// Find cost of all characters in
// both strings
for (int i = 0; i < m; ++i)
cost += X[i] - '0';
for (int i = 0; i < n; ++i)
cost += Y[i] - '0';
return cost - lcs(X, Y, m, n);
}
// Driver function
public static void Main()
{
string X = "3759";
string Y= "9350";
Console.WriteLine("Minimum Cost to make two strings"+
" identical is = " +findMinCost(X, Y));
}
}
// This code is contributed by vt_m
Output:
Source
https://www.geeksforgeeks.org/minimum-cost-make-two-strings-identical-deleting-digits/
1930
Chapter 266
Minimum cost to reach the top of the floor by climbing stairs - GeeksforGeeks
Given N non-negative integers which signifies the cost of the moving from each stair. Paying
the cost at i-th step, you can either climb one or two steps. Given that one can start from
the 0-the step or 1-the step, the task is to find the minimum cost to reach the top of the
floor(N+1) by climbing N stairs.
Examples:
Approach: Let dp[i] be the cost to climb the i-th staircase to from 0-th or 1-th step.
Hence dp[i] = cost[i] + min(dp[i-1], dp[i-2]). Since dp[i-1] and dp[i-2] is needed to
compute the cost of travelling from i-th step, a bottom-up approach can be used to solve
the problem. The answer will be the minimum of cost of reaching n-1th stair and n-2th
stair. Compute the dp[] array in bottom-up manner.
Below is the implementation of the above approach.
C++
1931
Chapter 266. Minimum cost to reach the top of the floor by climbing stairs
Java
1932
Chapter 266. Minimum cost to reach the top of the floor by climbing stairs
Python 3
1933
Chapter 266. Minimum cost to reach the top of the floor by climbing stairs
C#
1934
Chapter 266. Minimum cost to reach the top of the floor by climbing stairs
if (n == 1)
return cost[0];
// initially to
// climb till 0-th
// or 1th stair
dp[0] = cost[0];
dp[1] = cost[1];
// iterate for finding the cost
for (int i = 2; i < n; i++)
{
dp[i] = Math.Min(dp[i - 1],
dp[i - 2]) + cost[i];
}
// return the minimum
return Math.Min(dp[n - 2],
dp[n - 1]);
}
// Driver Code
public static void Main()
{
int []a = { 16, 19, 10, 12, 18 };
int n = a.Length;
Console.WriteLine(minimumCost(a, n));
}
}
// This code is contributed
// by Subhadeep
PHP
<?php
// PHP program to find the
// minimum cost required
// to reach the n-th floor
// function to find the minimum
// cost to reach N-th floor
function minimumCost(&$cost, $n)
{
// declare an array
// base case
if ($n == 1)
1935
Chapter 266. Minimum cost to reach the top of the floor by climbing stairs
return $cost[0];
// initially to climb
// till 0-th or 1th stair
$dp[0] = $cost[0];
$dp[1] = $cost[1];
// iterate for finding
// the cost
for ($i = 2; $i < $n; $i++)
{
$dp[$i] = min($dp[$i - 1],
$dp[$i - 2]) +
$cost[$i];
}
// return the minimum
return min($dp[$n - 2],
$dp[$n - 1]);
}
// Driver Code
$a = array(16, 19, 10, 12, 18);
$n = sizeof($a);
echo(minimumCost($a, $n));
// This code is contributed
// by Shivi_Aggarwal
?>
Output:
31
C++
1936
Chapter 266. Minimum cost to reach the top of the floor by climbing stairs
// space-optimized solution
#include <bits/stdc++.h>
using namespace std;
// function to find the minimum cost
// to reach N-th floor
int minimumCost(int cost[], int n)
{
int dp1 = 0, dp2 = 0;
// traverse till N-th stair
for (int i = 0; i < n; i++) {
int dp0 = cost[i] + min(dp1, dp2);
// update the last two stairs value
dp2 = dp1;
dp1 = dp0;
}
return min(dp1, dp2);
}
// Driver Code
int main()
{
int a[] = { 2, 5, 3, 1, 7, 3, 4 };
int n = sizeof(a) / sizeof(a[0]);
cout << minimumCost(a, n);
return 0;
}
Java
1937
Chapter 266. Minimum cost to reach the top of the floor by climbing stairs
Python 3
1938
Chapter 266. Minimum cost to reach the top of the floor by climbing stairs
a = [ 2, 5, 3, 1, 7, 3, 4 ]
n = len(a)
print(minimumCost(a, n))
# This code is contributed
# by ChitraNayal
C#
1939
Chapter 266. Minimum cost to reach the top of the floor by climbing stairs
PHP
<?php
// PHP program to find the
// minimum cost required to
// reach the n-th floor
// space-optimized solution
// function to find the minimum
// cost to reach N-th floor
function minimumCost(&$cost, $n)
{
$dp1 = 0;
$dp2 = 0;
// traverse till N-th stair
for ($i = 0; $i < $n; $i++)
{
$dp0 = $cost[$i] +
min($dp1, $dp2);
// update the last
// two stairs value
$dp2 = $dp1;
$dp1 = $dp0;
}
return min($dp1, $dp2);
}
// Driver Code
$a = array(2, 5, 3, 1, 7, 3, 4);
$n = sizeof($a);
echo (minimumCost($a, $n));
// This code is contributed
// by Shivi_Aggarwal
?>
Output:
1940
Chapter 266. Minimum cost to reach the top of the floor by climbing stairs
The following problem can be solved using top-down approach. In that case the recurrence
will be dp[i] = cost[i] + min(dp[i+1], dp[i+2]).
Improved By : Shivi_Aggarwal, tufan_gupta2000, ChitraNayal
Source
https://www.geeksforgeeks.org/minimum-cost-to-reach-the-top-of-the-floor-by-climbing-stairs/
1941
Chapter 267
Minimum cost to sort strings using reversal operations of different costs - GeeksforGeeks
Given an array of strings and costs of reversing all strings, we need to sort the array. We
cannot move strings in array, only string reversal is allowed. We need to reverse some of the
strings in such a way that all strings make a lexicographic order and cost is also minimized.
If it is not possible to sort strings in any way, output not possible.
Examples:
We can solve this problem using dynamic programming. We make a 2D array for storing
the minimum cost of sorting.
1942
Chapter 267. Minimum cost to sort strings using reversal operations of different costs
Computation of dp[i][0]
If arr[i] is greater than str[i-1], we update dp[i][0]
by dp[i-1][0]
If arr[i] is greater than reversal of previous string
we update dp[i][0] by dp[i-1][1]
C/C++
1943
Chapter 267. Minimum cost to sort strings using reversal operations of different costs
}
string curStr;
int curCost;
// looping for all strings
for (int i = 1; i < N; i++)
{
// Looping twice, once for string and once
// for reversed string
for (int j = 0; j < 2; j++)
{
dp[i][j] = INT_MAX;
// getting current string and current
// cost according to j
curStr = (j == 0) ? arr[i] : revStr[i];
curCost = (j == 0) ? 0 : cost[i];
// Update dp value only if current string
// is lexicographically larger
if (curStr >= arr[i - 1])
dp[i][j] = min(dp[i][j], dp[i-1][0] + curCost);
if (curStr >= revStr[i - 1])
dp[i][j] = min(dp[i][j], dp[i-1][1] + curCost);
}
}
// getting minimum from both entries of last index
int res = min(dp[N-1][0], dp[N-1][1]);
return (res == INT_MAX)? -1 : res;
}
// Driver code to test above methods
int main()
{
string arr[] = {"aa", "ba", "ac"};
int cost[] = {1, 3, 1};
int N = sizeof(arr) / sizeof(arr[0]);
int res = minCost(arr, cost, N);
if (res == -1)
cout << "Sorting not possible\n";
else
cout << "Minimum cost to sort strings is "
<< res;
}
1944
Chapter 267. Minimum cost to sort strings using reversal operations of different costs
Python
1945
Chapter 267. Minimum cost to sort strings using reversal operations of different costs
Output:
Source
https://www.geeksforgeeks.org/minimum-cost-sort-strings-using-reversal-operations-different-costs/
1946
Chapter 268
We can solve this problem using dynamic programming. The main thing to observe is that
moving an element doesn’t change the relative order of elements other than the element
which is being moved. Now consider longest increasing subsequenc (LIS)e in which equal
element are also taken as part of the increasing sequence, now if keep the element of this
increasing sequence as it is and move all other elements then it will take the least number of
steps because we have taken longest subsequence which does not need to be moved. Finally,
the answer will be the size of the array minus the size of the longest increasing subsequence.
As LIS problem can be solved in O(N^2) with O(N) extra space using Dynamic Program-
ming.
Below is the implementation of above idea.
C++
1947
Chapter 268. Minimum insertions to sort an array
Java
1948
Chapter 268. Minimum insertions to sort an array
class Main
{
// method returns min steps of insertion we need
// to perform to sort array 'arr'
static int minInsertionStepToSortArray(int arr[], int N)
{
// lis[i] is going to store length of lis
// that ends with i.
int[] lis = new int[N];
/* Initialize lis values for all indexes */
for (int i = 0; i < N; i++)
lis[i] = 1;
/* Compute optimized lis values in bottom up manner */
for (int i = 1; i < N; i++)
for (int j = 0; j < i; j++)
if (arr[i] >= arr[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* The overall LIS must end with of of the array
elements. Pick maximum of all lis values */
int max = 0;
for (int i = 0; i < N; i++)
if (max < lis[i])
max = lis[i];
// return size of array minus length of LIS
// as final result
return (N - max);
}
// Driver code to test above methods
public static void main (String[] args)
{
int arr[] = {2, 3, 5, 1, 4, 7, 6};
int N = arr.length;
System.out.println(minInsertionStepToSortArray(arr, N));
}
}
/* This code is contributed by Harsh Agarwal */
C#
1949
Chapter 268. Minimum insertions to sort an array
using System;
class GfG {
// method returns min steps of insertion
// we need to perform to sort array 'arr'
static int minInsertionStepToSortArray(
int []arr, int N)
{
// lis[i] is going to store length
// of lis that ends with i.
int[] lis = new int[N];
/* Initialize lis values for all
indexes */
for (int i = 0; i < N; i++)
lis[i] = 1;
/* Compute optimized lis values in
bottom up manner */
for (int i = 1; i < N; i++)
for (int j = 0; j < i; j++)
if (arr[i] >= arr[j] &&
lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* The overall LIS must end with of
of the array elements. Pick maximum
of all lis values */
int max = 0;
for (int i = 0; i < N; i++)
if (max < lis[i])
max = lis[i];
// return size of array minus length
// of LIS as final result
return (N - max);
}
// Driver code to test above methods
public static void Main (String[] args)
{
int []arr = {2, 3, 5, 1, 4, 7, 6};
int N = arr.Length;
Console.Write(
1950
Chapter 268. Minimum insertions to sort an array
minInsertionStepToSortArray(arr, N));
}
}
// This code is contributed by parashar.
PHP
<?php
// PHP program to get minimum
// number of insertion steps
// to sort an array
// method returns min steps of
// insertion we need to perform
// to sort array 'arr'
function minInsertionStepToSortArray($arr, $N)
{
// lis[i] is going to store
// length of lis that ends with i.
$lis[$N] = 0;
/* Initialize lis values
for all indexes */
for ($i = 0; $i < $N; $i++)
$lis[$i] = 1;
/* Compute optimized lis values
in bottom up manner */
for ($i = 1; $i < $N; $i++)
for ($j = 0; $j < $i; $j++)
if ($arr[$i] >= $arr[$j] &&
$lis[$i] < $lis[$j] + 1)
$lis[$i] = $lis[$j] + 1;
/* The overall LIS must end with
of of the array elements. Pick
maximum of all lis values */
$max = 0;
for ($i = 0; $i < $N; $i++)
if ($max < $lis[$i])
$max = $lis[$i];
// return size of array minus
// length of LIS as final result
return ($N - $max);
}
1951
Chapter 268. Minimum insertions to sort an array
// Driver code
$arr = array(2, 3, 5, 1, 4, 7, 6);
$N = sizeof($arr) / sizeof($arr[0]);
echo minInsertionStepToSortArray($arr, $N);
// This code is contributed by nitin mittal
?>
Output :
Source
https://www.geeksforgeeks.org/minimum-insertions-sort-array/
1952
Chapter 269
1953
Chapter 269. Minimum jumps to reach last building in a matrix
# define R 4
# define C 3
bool isSafe(int x, int y)
{
return (x < R && y < C);
}
/* Returns minimum jump path from (0, 0) to
(m, n) in hight[R][C]*/
int minJump(int height[R][C], int x, int y)
{
// base case
if (x == R - 1 && y == C - 1)
return 0;
// Find minimum jumps if we go through diagonal
int diag = INT_MAX;
if (isSafe(x + 1, y + 1))
diag = minJump(height, x + 1, y + 1) +
abs(height[x][y] - height[x + 1][y + 1]);
// Find minimum jumps if we go through down
int down = INT_MAX;
if (isSafe(x + 1, y))
down = minJump(height, x + 1, y) +
abs(height[x][y] - height[x + 1][y]);
// Find minimum jumps if we go through right
int right = INT_MAX;
if (isSafe(x, y + 1))
right = minJump(height, x, y + 1) +
abs(height[x][y] - height[x][y + 1]);
// return minimum jumps
return min({down, right, diag});
}
/* Driver program to test above functions */
int main()
{
int height[][C] = { { 5, 4, 2 },
{ 9, 2, 1 },
{ 2, 5, 9 },
{ 1, 3, 11 } };
cout << minJump(height, 0, 0);
return 0;
1954
Chapter 269. Minimum jumps to reach last building in a matrix
Java
1955
Chapter 269. Minimum jumps to reach last building in a matrix
right = minJump(height, x, y + 1) +
Math.abs(height[x][y] - height[x][y + 1]);
// return minimum jumps
return Math.min(down, Math.min(right, diag));
}
// Driver program
public static void main(String[] args)
{
int height[][] = { { 5, 4, 2 },
{ 9, 2, 1 },
{ 2, 5, 9 },
{ 1, 3, 11} };
System.out.println(minJump(height, 0, 0));
}
}
// This article is contributed by Prerna Saini.
C#
// Recursive C# program
// to find minimum jumps
// to reach last building
// from first.
using System;
class GFG {
static bool isSafe(int x, int y)
{
return (x < 4 && y < 3);
}
// Returns minimum jump
// path from (0, 0) to
// (m, n) in hight[R][C]
static int minJump(int [,]height,
int x, int y)
{
// base case
if (x == 4 - 1 && y == 3 - 1)
return 0;
// Find minimum jumps
1956
Chapter 269. Minimum jumps to reach last building in a matrix
// if we go through
// diagonal
int diag = int.MaxValue;
if (isSafe(x + 1, y + 1))
diag = minJump(height, x + 1, y + 1) +
Math.Abs(height[x,y] -
height[x + 1,y + 1]);
// Find minimum jumps
// if we go through
// down
int down = int.MaxValue;
if (isSafe(x + 1, y))
down = minJump(height, x + 1, y) +
Math.Abs(height[x,y] -
height[x + 1,y]);
// Find minimum jumps
// if we go through right
int right = int.MaxValue;
if (isSafe(x, y + 1))
right = minJump(height, x, y + 1) +
Math.Abs(height[x,y] -
height[x,y + 1]);
// return minimum jumps
return Math.Min(down, Math.Min(right, diag));
}
// Driver code
public static void Main()
{
int [,]height = {{5, 4, 2},
{9, 2, 1},
{2, 5, 9},
{1, 3, 11}};
Console.Write(minJump(height, 0, 0));
}
}
// This code is contributed by nitin mittal
PHP
1957
Chapter 269. Minimum jumps to reach last building in a matrix
<?php
// Recursive PHP program to
// find minimum jumps to
// reach last building from first.
$R = 4;
$C = 3;
function isSafe($x, $y)
{
global $R, $C;
return ($x < $R and $y < $C);
}
// Returns minimum jump
// path from (0, 0) to
// (m, n) in hight[R][C]
function minJump($height, $x, $y)
{
global $R, $C;
// base case
if ($x == $R - 1 and $y == $C - 1)
return 0;
// Find minimum jumps if
// we go through diagonal
$diag = PHP_INT_MAX;
if (isSafe($x + 1, $y + 1))
$diag = minJump($height, $x + 1, $y + 1) +
abs($height[$x][$y] -
$height[$x + 1][$y + 1]);
// Find minimum jumps
// if we go through down
$down = PHP_INT_MAX;
if (isSafe($x + 1, $y))
$down = minJump($height, $x + 1, $y) +
abs($height[$x][$y] -
$height[$x + 1][$y]);
// Find minimum jumps if
// we go through right
$right = PHP_INT_MAX;
if (isSafe($x, $y + 1))
$right = minJump($height, $x, $y + 1) +
abs($height[$x][$y] -
$height[$x][$y + 1]);
1958
Chapter 269. Minimum jumps to reach last building in a matrix
// return minimum jumps
return min($down, min($right, $diag));
}
// Driver Code
$height = array(array( 5, 4, 2 ),
array( 9, 2, 1 ),
array( 2, 5, 9 ),
array( 1, 3, 11 ));
echo minJump($height, 0, 0);
// This code is contributed by anuj_67.
?>
Output :
12
1959
Chapter 269. Minimum jumps to reach last building in a matrix
Output:
12
1960
Chapter 269. Minimum jumps to reach last building in a matrix
Source
https://www.geeksforgeeks.org/minimum-jumps-to-reach-last-building-in-a-matrix/
1961
Chapter 270
Minimum number of deletions and insertions to transform one string into another - Geeks-
forGeeks
Given two strings ‘str1’ and ‘str2’ of size m and n respectively. The task is to remove/delete
and insert minimum number of characters from/in str1 so as to transform it into str2. It
could be possible that the same character needs to be removed/deleted from one point of
str1 and inserted to some another point.
Examples:
A simple solution is to consider all subsequences of str1 and for each subsequence calculate
1962
Chapter 270. Minimum number of deletions and insertions to transform one string into
another
minimum deletions and insertions so as to transform it into str2. A very complex method
and the time complexity of this solution is exponential.
An efficient approach uses the concept of finding the length of the longest common sub-
sequence of the given two sequences.
Algorithm:
C++
1963
Chapter 270. Minimum number of deletions and insertions to transform one string into
another
}
}
// L[m][n] contains length of LCS
// for X[0..n-1] and Y[0..m-1]
return L[m][n];
}
// function to find minimum number
// of deletions and insertions
void printMinDelAndInsert(string str1, string str2)
{
int m = str1.size();
int n = str2.size();
int len = lcs(str1, str2, m, n);
cout << "Minimum number of deletions = "
<< (m - len) << endl;
cout << "Minimum number of insertions = "
<< (n - len) << endl;
}
// Driver program to test above
int main()
{
string str1 = "heap";
string str2 = "pea";
printMinDelAndInsert(str1, str2);
return 0;
}
Java
1964
Chapter 270. Minimum number of deletions and insertions to transform one string into
another
1965
Chapter 270. Minimum number of deletions and insertions to transform one string into
another
C#
1966
Chapter 270. Minimum number of deletions and insertions to transform one string into
another
Output:
Source
https://www.geeksforgeeks.org/minimum-number-deletions-insertions-transform-one-string-another/
1967
Chapter 271
Input : {5, 6, 1, 7, 4}
Output : 2
Removing 1 and 4
leaves the remaining sequence order as
5 6 7 which is a sorted sequence.
A simple solution is to remove all subsequences one by one and check if remaining set of
elements are in sorted order or not. Time complexity of this solution is exponential.
An efficient approach uses the concept of finding the length of the longest increasing
subsequence of a given sequence.
Algorithm:
1968
Chapter 271. Minimum number of deletions to make a sorted sequence
C++
1969
Chapter 271. Minimum number of deletions to make a sorted sequence
Java
1970
Chapter 271. Minimum number of deletions to make a sorted sequence
Python3
1971
Chapter 271. Minimum number of deletions to make a sorted sequence
result = 0
lis = [0 for i in range(n)]
# Initialize LIS values
# for all indexes
for i in range(n):
lis[i] = 1
# Compute optimized LIS values
# in bottom up manner
for i in range(1, n):
for j in range(i):
if ( arr[i] > arr[j] and
lis[i] < lis[j] + 1):
lis[i] = lis[j] + 1
# Pick resultimum
# of all LIS values
for i in range(n):
if (result < lis[i]):
result = lis[i]
return result
# Function to calculate minimum
# number of deletions
def minimumNumberOfDeletions(arr, n):
# Find longest increasing
# subsequence
len = lis(arr, n)
# After removing elements
# other than the lis, we
# get sorted sequence.
return (n - len)
# Driver Code
arr = [30, 40, 2, 5, 1,
7, 45, 50, 8]
n = len(arr)
print("Minimum number of deletions = ",
minimumNumberOfDeletions(arr, n))
# This code is contributed by Anant Agarwal.
1972
Chapter 271. Minimum number of deletions to make a sorted sequence
C#
// C# implementation to find
// minimum number of deletions
// to make a sorted sequence
using System;
class GfG
{
/* lis() returns the length of
the longest increasing subsequence
in arr[] of size n */
static int lis( int []arr, int n )
{
int result = 0;
int[] lis = new int[n];
/* Initialize LIS values for
all indexes */
for (int i = 0; i < n; i++ )
lis[i] = 1;
/* Compute optimized LIS values
in bottom up manner */
for (int i = 1; i < n; i++ )
for (int j = 0; j < i; j++ )
if ( arr[i] > arr[j] &&
lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* Pick resultimum of all LIS
values */
for (int i = 0; i < n; i++ )
if (result < lis[i])
result = lis[i];
return result;
}
// function to calculate minimum
// number of deletions
static int minimumNumberOfDeletions(
int []arr, int n)
{
// Find longest increasing
// subsequence
1973
Chapter 271. Minimum number of deletions to make a sorted sequence
PHP
<?php
// PHP implementation to find
// minimum number of deletions
// to make a sorted sequence
/* lis() returns the length of
the longest increasing subsequence
in arr[] of size n */
function lis( $arr, $n )
{
$result = 0;
$lis[$n] = 0;
/* Initialize LIS values
for all indexes */
for ($i = 0; $i < $n; $i++ )
$lis[$i] = 1;
/* Compute optimized LIS
values in bottom up manner */
for ($i = 1; $i < $n; $i++ )
for ($j = 0; $j < $i; $j++ )
if ( $arr[$i] > $arr[$j] &&
1974
Chapter 271. Minimum number of deletions to make a sorted sequence
Output :
1975
Chapter 271. Minimum number of deletions to make a sorted sequence
Source
https://www.geeksforgeeks.org/minimum-number-deletions-make-sorted-sequence/
1976
Chapter 272
Examples :
Input : aebcbda
Output : 2
Remove characters 'e' and 'd'
Resultant string will be 'abcba'
which is a palindromic string
Input : geeksforgeeks
Output : 8
A simple solution is to remove all subsequences one by one and check if remaining string
is palindrome or not. Time complexity of this solution is exponential.
An efficient approach uses the concept of finding the length of the longest palindromic
subsequence of a given sequence.
Algorithm:
1977
Chapter 272. Minimum number of deletions to make a string palindrome
C++
1978
Chapter 272. Minimum number of deletions to make a string palindrome
}
// length of longest
// palindromic subseq
return L[0][n - 1];
}
// function to calculate
// minimum number of deletions
int minimumNumberOfDeletions(string str)
{
int n = str.size();
// Find longest palindromic
// subsequence
int len = lps(str);
// After removing characters
// other than the lps, we
// get palindrome.
return (n - len);
}
// Driver Code
int main()
{
string str = "geeksforgeeks";
cout << "Minimum number of deletions = "
<< minimumNumberOfDeletions(str);
return 0;
}
Java
1979
Chapter 272. Minimum number of deletions to make a string palindrome
1980
Chapter 272. Minimum number of deletions to make a string palindrome
return (n - len);
}
// Driver Code
public static void main(String[] args)
{
String str = "geeksforgeeks";
System.out.println("Minimum number " +
"of deletions = "+
minimumNumberOfDeletions(str));
}
}
// This code is contributed by Sumit Ghosh
C#
// C# implementation to find
// minimum number of deletions
// to make a string palindromic
using System;
class GFG
{
// Returns the length of
// the longest palindromic
// subsequence in 'str'
static int lps(String str)
{
int n = str.Length;
// Create a table to store
// results of subproblems
int [,]L = new int[n, n];
// Strings of length 1
// are palindrome of length 1
for (int i = 0; i < n; i++)
L[i, i] = 1;
// Build the table. Note
// that the lower diagonal
// values of table are useless
// and not filled in the process.
// c1 is length of substring
for (int cl = 2; cl <= n; cl++)
{
for (int i = 0; i < n - cl + 1; i++)
1981
Chapter 272. Minimum number of deletions to make a string palindrome
{
int j = i + cl - 1;
if (str[i] == str[j] && cl == 2)
L[i, j] = 2;
else if (str[i] == str[j])
L[i, j] = L[i + 1, j - 1] + 2;
else
L[i, j] = Math.Max(L[i, j - 1],
L[i + 1, j]);
}
}
// length of longest
// palindromic subsequence
return L[0, n - 1];
}
// function to calculate minimum
// number of deletions
static int minimumNumberOfDeletions(string str)
{
int n = str.Length;
// Find longest palindromic
// subsequence
int len = lps(str);
// After removing characters
// other than the lps, we get
// palindrome.
return (n - len);
}
// Driver Code
public static void Main()
{
string str = "geeksforgeeks";
Console.Write("Minimum number of" +
" deletions = " +
minimumNumberOfDeletions(str));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
1982
Chapter 272. Minimum number of deletions to make a string palindrome
1983
Chapter 272. Minimum number of deletions to make a string palindrome
}
// function to calculate minimum
// number of deletions
function minimumNumberOfDeletions($str)
{
$n = strlen($str);
// Find longest
// palindromic subsequence
$len = lps($str);
// After removing characters
// other than the lps, we get
// palindrome.
return ($n - $len);
}
// Driver Code
{
$str = "geeksforgeeks";
echo "Minimum number of deletions = ",
minimumNumberOfDeletions($str);
return 0;
}
// This code is contributed by nitin mittal.
?>
Output :
Source
https://www.geeksforgeeks.org/minimum-number-deletions-make-string-palindrome/
1984
Chapter 273
Input : baca
Output : 1
Input : geek
Output : 2
1985
Chapter 273. Minimum number of deletions to make a string palindrome | Set 2
Output:
12
Time complexity: O( )
1986
Chapter 273. Minimum number of deletions to make a string palindrome | Set 2
Space complexity: O( )
where is length of string
Why is it working?
To understand it we need to start from the very beginning of how we create dp[][], for
example for word “geek”, it initially looks like this:
Both 1st row and 1st column are filled with number 1..4 as this is the number of modifications
needed to create empty string, i.e:
[0][1] == 1, to create empty string from letter ‘g’ remove this one letter
[0][2] == 2, to create empty string from letters “ge”, remove both those letters, etc.
The same story for first column:
[1][0] == 1, to create empty string from letter ‘k’ remove this one letter
[2][0] == 2, to create empty string from letters “ke”, remove both those letters, etc.
Now, we are using dynamic programming approach to get the minimum number of modifi-
cations to get every other substring to become second substring, and at the end out dp[][]
looks like this:
So for example minimum number of modifications to get substring ‘gee’ from ‘kee’ is 2. So
far so good but this algorithm is doing two things, it is both inserting and deleting characters,
and we are only interested in number of removals. So let’s one more time take a look at our
resulting array, for example at entry [4][1], this entry states:
[4][1] – to make string ‘g’ from string “keeg” we need to perform 3 modifications(which is
just delete chars “kee”)
1987
Chapter 273. Minimum number of deletions to make a string palindrome | Set 2
[3][2] – to make string “ge” from “kee” we need to perform 3 modifications also by removing
from first string ‘g’ and from second ‘ke’
So basically every time we will be moving diagonally up, from left corner we will get number
of removals to get the same substring backwards. Thing to notice here is that it is like having
on string two pointers, one moving from beginning and other from end. Very important spot
is that strings do not necessary has to have even number of characters, so this is the reason
we also has to check upper and lower values in dp[][].
Source
https://www.geeksforgeeks.org/minimum-number-deletions-make-string-palindrome-set-2/
1988
Chapter 274
Minimum number of elements which are not part of Increasing or decreasing subsequence
in array - GeeksforGeeks
Given an array of n elements. Make strictly increasing and strictly decreasing subsequences
from the array such that each array element belongs to increasing subsequence or decreasing
subsequence, but not both, or can be part of none of the subsequence. Minimize the number
of elements which are not part of any of the subsequences and find the count of such elements.
Examples:
Input : arr[] = { 7, 8, 1, 2, 4, 6, 3, 5, 2, 1, 8, 7 }
Output : 2
Increasing sequence can be { 1, 2, 4, 5, 8 }.
Decreasing sequence can be { 7, 6, 3, 2, 1 }.
So, only 2 (8, 7) element is left which are not part of
either of the subsequences.
Input : arr[] = { 1, 4, 2, 3, 3, 2, 4, 1 }
Output : 0
Increasing sequence can be { 1, 2, 3, 4 }.
Decreasing sequence can be { 4, 3, 2, 1 }.
So, no element is left which is not part of either of
the subsequences.
1989
Chapter 274. Minimum number of elements which are not part of Increasing or decreasing
subsequence in array
The idea is to make a decision on each index, starting from index 0, one by one. For each
index there can be three possibilities, first, it can belong to increasing sequence, second, it
can belong to decreasing sequence, third, it does not belong to any of these sequences.
So, for each index, check for the optimal answer (minimum element which is not part of any
of the subsequences) by considering it once as a part of increasing subsequence or as a part
of decreasing subsequence. If the optimal answer cannot be achieved by them then leave it
as the element which is not part of any of the sequence.
To decrease the complexity (using Dynamic Programming), we can store the number of
elements which are not part of any of the subsequences using 3D array dp[x][y][z], where x
indicates the decision index, y indicates the last index of decreasing sequence, z indicates
the last index of increasing sequence.
Below is C++ implementation of this approach:
1990
Chapter 274. Minimum number of elements which are not part of Increasing or decreasing
subsequence in array
else
dp[dec][inc][i] = min(countMin(arr, dp, n, dec, i, i + 1),
dp[dec][inc][i]);
}
// If element cannot be part of any of the sequence.
if (dp[dec][inc][i] == -1)
dp[dec][inc][i] = 1 + countMin(arr, dp, n, dec, inc, i + 1);
// After considering element as part of increasing and
// decreasing sequence trying as not part of any of the
// sequence.
else
dp[dec][inc][i] = min(1 + countMin(arr, dp, n, dec, inc, i + 1),
dp[dec][inc][i]);
return dp[dec][inc][i];
}
// Wrapper Function
int wrapper(int arr[], int n)
{
// Adding two number at the end of array, so that
// increasing and decreasing sequence can be made.
// MAX - 2 index is assigned INT_MAX for decreasing sequence
// because/ next number of sequence must be less than it.
// Similarly, for Increasing sequence INT_MIN is assigned to
// MAX - 1 index.
arr[MAX - 2] = INT_MAX;
arr[MAX - 1] = INT_MIN;
int dp[MAX][MAX][MAX];
memset(dp, -1, sizeof dp);
return countMin(arr, dp, n, MAX - 2, MAX - 1, 0);
}
// Driven Program
int main()
{
int n = 12;
int arr[MAX] = { 7, 8, 1, 2, 4, 6, 3, 5, 2, 1, 8, 7 };
cout << wrapper(arr, n) << endl;
return 0;
}
Output:
1991
Chapter 274. Minimum number of elements which are not part of Increasing or decreasing
subsequence in array
Source
https://www.geeksforgeeks.org/minimum-number-of-elements-which-are-not-part-of-increasing-or-decreasing-subse
1992
Chapter 275
First element is 1, so can only go to 3. Second element is 3, so can make at most 3 steps eg
to 5 or 8 or 9.
Method 1 (Naive Recursive Approach)
A naive approach is to start from the first element and recursively call for all the elements
reachable from first element. The minimum number of jumps to reach end from first can be
calculated using minimum number of jumps needed to reach end from the elements reachable
from first.
minJumps(start, end) = Min ( minJumps(k, end) ) for all k reachable from start
C
#include <stdio.h>
#include <limits.h>
// Returns minimum number of jumps to reach arr[h] from arr[l]
int minJumps(int arr[], int l, int h)
1993
Chapter 275. Minimum number of jumps to reach end
{
// Base case: when source and destination are same
if (h == l)
return 0;
// When nothing is reachable from the given source
if (arr[l] == 0)
return INT_MAX;
// Traverse through all the points reachable from arr[l]. Recursively
// get the minimum number of jumps needed to reach arr[h] from these
// reachable points.
int min = INT_MAX;
for (int i = l+1; i <= h && i <= l + arr[l]; i++)
{
int jumps = minJumps(arr, i, h);
if(jumps != INT_MAX && jumps + 1 < min)
min = jumps + 1;
}
return min;
}
// Driver program to test above function
int main()
{
int arr[] = {1, 3, 6, 3, 2, 3, 6, 8, 9, 5};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Minimum number of jumps to reach end is %d ", minJumps(arr, 0, n-1));
return 0;
}
Java
1994
Chapter 275. Minimum number of jumps to reach end
return 0;
// When nothing is reachable
// from the given source
if (arr[l] == 0)
return Integer.MAX_VALUE;
// Traverse through all the points
// reachable from arr[l]. Recursively
// get the minimum number of jumps
// needed to reach arr[h] from these
// reachable points.
int min = Integer.MAX_VALUE;
for (int i = l+1; i <= h && i <= l + arr[l]; i++)
{
int jumps = minJumps(arr, i, h);
if(jumps != Integer.MAX_VALUE &&
jumps + 1 < min)
min = jumps + 1;
}
return min;
}
// Driver code
public static void main(String args[])
{
int arr[] = {1, 3, 6, 3, 2, 3, 6, 8, 9, 5};
int n = arr.length;
System.out.print("Minimum number of jumps to reach end is "
+ minJumps(arr, 0, n-1));
}
}
// This code is contributed by Sahil_Bansall
Python3
1995
Chapter 275. Minimum number of jumps to reach end
if (h == l):
return 0
# when nothing is reachable
# from the given source
if (arr[l] == 0):
return float('inf')
# Traverse through all the points
# reachable from arr[l]. Recursively
# get the minimum number of jumps
# needed to reach arr[h] from
# these reachable points.
min = float('inf')
for i in range(l + 1, h + 1):
if (i < l + arr[l] + 1):
jumps = minJumps(arr, i, h)
if (jumps != float('inf') and
jumps + 1 < min):
min = jumps + 1
return min
# Driver program to test above function
arr = [1, 3, 6, 3, 2, 3, 6, 8, 9, 5]
n = len(arr)
print('Minimum number of jumps to reach',
'end is', minJumps(arr, 0, n-1))
# This code is contributed by Soumen Ghosh
C#
1996
Chapter 275. Minimum number of jumps to reach end
PHP
<?php
// php program to find Minimum
// number of jumps to reach end
// Returns minimum number of jumps
// to reach arr[h] from arr[l]
function minJumps($arr, $l, $h)
{
// Base case: when source and
// destination are same
1997
Chapter 275. Minimum number of jumps to reach end
Output:
If we trace the execution of this method, we can see that there will be overlapping sub-
problems. For example, minJumps(3, 9) will be called two times as arr[3] is reachable from
arr[1] and arr[2]. So this problem has both properties (optimal substructure and overlapping
subproblems) of Dynamic Programming.
Method 2 (Dynamic Programming)
In this method, we build a jumps[] array from left to right such that jumps[i] indicates the
1998
Chapter 275. Minimum number of jumps to reach end
minimum number of jumps needed to reach arr[i] from arr[0]. Finally, we return jumps[n-1].
C / C++
#include <stdio.h>
#include <limits.h>
int min(int x, int y) { return (x < y)? x: y; }
// Returns minimum number of jumps to reach arr[n-1] from arr[0]
int minJumps(int arr[], int n)
{
int *jumps = new int[n]; // jumps[n-1] will hold the result
int i, j;
if (n == 0 || arr[0] == 0)
return INT_MAX;
jumps[0] = 0;
// Find the minimum number of jumps to reach arr[i]
// from arr[0], and assign this value to jumps[i]
for (i = 1; i < n; i++)
{
jumps[i] = INT_MAX;
for (j = 0; j < i; j++)
{
if (i <= j + arr[j] && jumps[j] != INT_MAX)
{
jumps[i] = min(jumps[i], jumps[j] + 1);
break;
}
}
}
return jumps[n-1];
}
// Driver program to test above function
int main()
{
int arr[] = {1, 3, 6, 1, 0, 9};
int size = sizeof(arr)/sizeof(int);
printf("Minimum number of jumps to reach end is %d ", minJumps(arr,size));
return 0;
}
Java
1999
Chapter 275. Minimum number of jumps to reach end
Python3
2000
Chapter 275. Minimum number of jumps to reach end
C#
2001
Chapter 275. Minimum number of jumps to reach end
jumps[0] = 0;
// Find the minimum number of
// jumps to reach arr[i]
// from arr[0], and assign
// this value to jumps[i]
for (int i = 1; i < n; i++)
{
jumps[i] = int.MaxValue;
for (int j = 0; j < i; j++)
{
if (i <= j + arr[j] && jumps[j] != int.MaxValue )
{
jumps[i] = Math.Min(jumps[i], jumps[j] + 1);
break;
}
}
}
return jumps[n - 1];
}
// Driver program
public static void Main()
{
int []arr = {1, 3, 6, 1, 0, 9};
Console.Write("Minimum number of jumps to reach end is : "+
minJumps(arr,arr.Length));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP code for Minimum number of
// jumps to reach end
// Returns minimum number of jumps
// to reach arr[n-1] from arr[0]
function minJumps($arr, $n)
{
// jumps[n-1] will
// hold the result
$jumps = array($n);
if ($n == 0 || $arr[0] == 0)
2002
Chapter 275. Minimum number of jumps to reach end
return 999999;
$jumps[0] = 0;
// Find the minimum number of
// jumps to reach arr[i]
// from arr[0], and assign
// this value to jumps[i]
for ($i = 1; $i < $n; $i++)
{
$jumps[$i] = 999999;
for ($j = 0; $j < $i; $j++)
{
if ($i <= $j + $arr[$j] &&
$jumps[$j] != 999999)
{
$jumps[$i] = min($jumps[$i],
$jumps[$j] + 1);
break;
}
}
}
return $jumps[$n-1];
}
// Driver Code
$arr = array(1, 3, 6, 1, 0, 9);
$size = count($arr);
echo "Minimum number of jumps to reach end is ".
minJumps($arr, $size);
// This code is contributed by Sam007
?>
Output:
C++
2003
Chapter 275. Minimum number of jumps to reach end
2004
Chapter 275. Minimum number of jumps to reach end
Python3
2005
Chapter 275. Minimum number of jumps to reach end
2006
Chapter 275. Minimum number of jumps to reach end
n = len(arr)
print('Minimum number of jumps to reach',
'end is', minJumps(arr, n-1))
# This code is contributed by Soumen Ghosh
Java
2007
Chapter 275. Minimum number of jumps to reach end
// Otherwise, to find out
// the minimum number of
// jumps needed to reach
// arr[n-1], check all the
// points reachable from
// here and jumps[] value
// for those points
else
{
// initialize min value
min = Integer.MAX_VALUE;
// following loop checks
// with all reachable points
// and takes the minimum
for (int j = i + 1; j < n &&
j <= arr[i] + i; j++)
{
if (min > jumps[j])
min = jumps[j];
}
// Handle overflow
if (min != Integer.MAX_VALUE)
jumps[i] = min + 1;
else
jumps[i] = min; // or Integer.MAX_VALUE
}
}
return jumps[0];
}
// Driver Code
public static void main(String[] args)
{
int[] arr = {1, 3, 6, 1, 0, 9};
int size = arr.length;
System.out.println("Minimum number of" +
" jumps to reach end is " +
minJumps(arr, size));
}
}
// This code is contributed by mits.
2008
Chapter 275. Minimum number of jumps to reach end
Output:
Source
https://www.geeksforgeeks.org/minimum-number-of-jumps-to-reach-end-of-a-given-array/
2009
Chapter 276
1. maxReach The variable maxReach stores at all time the maximal reachable index in
the array.
2. step The variable step stores the number of steps we can still take(and is initialized
with value at index 0,i.e. initial number of steps)
3. jump jump stores the amount of jumps necessary to reach that maximal reachable
position.
2010
Chapter 276. Minimum number of jumps to reach end | Set 2 (O(n) solution)
• maxReach = arr[0]; // arr[0] = 1, so the maximum index we can reach at the moment
is 1.
step = arr[0]; // arr[0] = 1, the amount of steps we can still take is also 1.
jump = 1; // we will always need to take at least one jump.
• Now, starting iteration from index 1, the above values are updated as follows:
1. First we test whether we have reached the end of the array, in that case we just
need to return the jump variable.
if (i == arr.length - 1)
return jump;
2. Next we update the maxReach. This is equal to the maximum of maxReach and
i+arr[i](the number of steps we can take from the current position).
maxReach = Math.max(maxReach,i+arr[i]);
3. We used up a step to get to the current index, so steps has to be decreased.
step--;
4. If no more steps are remaining (i.e. steps=0, then we must have used a jump.
Therefore increase jump. Since we know that it is possible somehow to reach
maxReach, we again initialize the steps to the number of steps to reach maxReach
from position i. But before re-initializing step, we also check whether a step is
becoming zero or negative. In this case, It is not possible to reach further.
if (step == 0) {
jump++;
if(i>=maxReach)
return -1;
step = maxReach - i;
}
2011
Chapter 276. Minimum number of jumps to reach end | Set 2 (O(n) solution)
return 0;
// Return -1 if not possible to jump
if (arr[0] == 0)
return -1;
// initialization
int maxReach = arr[0]; // stores all time the maximal reachable index in the array.
int step = arr[0]; // stores the number of steps we can still take
int jump =1;//stores the number of jumps necessary to reach that maximal reachable position.
// Start traversing array
int i=1;
for (i = 1; i < n; i++)
{
// Check if we have reached the end of the array
if (i == n-1)
return jump;
// updating maxReach
maxReach = max(maxReach, i+arr[i]);
// we use a step to get to the current index
step--;
// If no further steps left
if (step == 0)
{
// we must have used a jump
jump++;
// Check if the current index/position or lesser index
// is the maximum reach point from the previous indexes
if(i >= maxReach)
return -1;
// re-initialize the steps to the amount
// of steps to reach maxReach from position i.
step = maxReach - i;
}
}
return -1;
}
// Driver program to test above function
int main()
{
2012
Chapter 276. Minimum number of jumps to reach end | Set 2 (O(n) solution)
Java
2013
Chapter 276. Minimum number of jumps to reach end | Set 2 (O(n) solution)
jump++;
//Check if the current index/position or lesser index
// is the maximum reach point from the previous indexes
if(i>=maxReach)
return -1;
// re-initialize the steps to the amount
// of steps to reach maxReach from position i.
step = maxReach - i;
}
}
return -1;
}
// Driver method to test the above function
public static void main(String[] args)
{
int arr[] = new int[] {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
// calling minJumps method
System.out.println(minJumps(arr));
}
}
Python
2014
Chapter 276. Minimum number of jumps to reach end | Set 2 (O(n) solution)
# Start traversing array
for i in range(1,n):
# Check if we have reached the end of the array
if (i == n-1):
return jump
# updating maxReach
maxReach = max(maxReach, i+arr[i])
# we use a step to get to the current index
step -= 1;
# If no further steps left
if (step == 0):
# we must have used a jump
jump += 1
# Check if the current index/position or lesser index
# is the maximum reach point from the previous indexes
if(i >= maxReach):
return -1
# re-initialize the steps to the amount
# of steps to reach maxReach from position i.
step = maxReach - i;
return -1
# Driver program to test above function
arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
size = len(arr)
# Calling the minJumps function
print("Minimum number of jumps to reach end is %d " %minJumps(arr,size))
# This code is contributed by Aditi Sharma
C#
2015
Chapter 276. Minimum number of jumps to reach end | Set 2 (O(n) solution)
2016
Chapter 276. Minimum number of jumps to reach end | Set 2 (O(n) solution)
}
return -1;
}
// Driver Code
public static void Main()
{
int []arr = new int[] {1, 3, 5, 8, 9, 2,
6, 7, 6, 8, 9};
// calling minJumps method
Console.Write(minJumps(arr));
}
}
// This code is contributed
// by nitin mittal
Output:
References :- Stackoverflow
Thanks to Chiranjeev Jain for suggesting this solution.
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/minimum-number-jumps-reach-endset-2on-solution/
2017
Chapter 277
Minimum number of single digit primes required whose sum is equal to N - GeeksforGeeks
Find the minimum number of single-digit prime numbers required whose sum will be equal
to N.
Examples:
Input: 11
Output: 3
Explanation: 5 + 3 + 3.
Another possibility is 3 + 3 + 3 + 2, but it is not
the minimal
Input: 12
Output: 2
Explanation: 7 + 5
Approach: Dynamic Programming can be used to solve the above problem. The observa-
tions are:
Using these observations, built a recurrence to solve this problem. The recurrence will be:
2018
Chapter 277. Minimum number of single digit primes required whose sum is equal to N
For {2, 3, 5, 7}, the answer would be 1. For each other number, using Observation 3, try
to find the minimum value possible, if possible.
Below is the implementation of the above approach.
C++
2019
Chapter 277. Minimum number of single digit primes required whose sum is equal to N
}
// Not possible
if (dp[n] == (1e9))
return -1;
else
return dp[n];
}
// Driver Code
int main()
{
int n = 12;
int minimal = MinimumPrimes(n);
if (minimal != -1)
cout << "Minimum number of single"
<< " digit primes required : "
<< minimal << endl;
else
cout << "Not possible";
return 0;
}
Java
2020
Chapter 277. Minimum number of single digit primes required whose sum is equal to N
2021
Chapter 277. Minimum number of single digit primes required whose sum is equal to N
}
// This code is contributed ankita_saini
Python 3
2022
Chapter 277. Minimum number of single digit primes required whose sum is equal to N
C#
2023
Chapter 277. Minimum number of single digit primes required whose sum is equal to N
if (check(i, 3))
dp[i] = Math.Min(dp[i], 1 +
dp[i - 3]);
if (check(i, 5))
dp[i] = Math.Min(dp[i], 1 +
dp[i - 5]);
if (check(i, 7))
dp[i] = Math.Min(dp[i], 1 +
dp[i - 7]);
}
// Not possible
if (dp[n] == (1e9))
return -1;
else
return dp[n];
}
// Driver Code
public static void Main(String []args)
{
int n = 12;
int minimal = (int)MinimumPrimes(n);
if (minimal != -1)
Console.WriteLine("Minimum number of single " +
"digit primes required: " +
minimal);
else
Console.WriteLine("Not Possible");
}
}
// This code is contributed
// by Ankita_Saini
PHP
<?php
// PHP program to find the minimum
// number of single digit prime
// numbers required which when summed
// equals to a given number N.
2024
Chapter 277. Minimum number of single digit primes required whose sum is equal to N
2025
Chapter 277. Minimum number of single digit primes required whose sum is equal to N
// Driver Code
$n = 12;
$minimal = MinimumPrimes($n);
if ($minimal != -1)
{
echo("Minimum number of single " .
"digit primes required :");
echo( $minimal );
}
else
{
echo("Not possible");
}
// This code is contributed
// by Shivi_Aggarwal
?>
Output:
Source
https://www.geeksforgeeks.org/minimum-number-of-single-digit-primes-required-whose-sum-is-equal-to-n/
2026
Chapter 278
Input: n = 100
Output: 1
100 can be written as 102. Note that 100 can also be
written as 52 + 52 + 52 + 52, but this
representation requires 4 squares.
Input: n = 6
Output: 3
The idea is simple, we start from 1 and go till a number whose square is smaller than or
equals to n. For every number x, we recur for n-x. Below is the recursive formula.
C++
2027
Chapter 278. Minimum number of squares whose sum equals to given number n
Java
2028
Chapter 278. Minimum number of squares whose sum equals to given number n
// getMinSquares rest of the table using recursive
// formula
int res = n; // Maximum squares required is
// n (1*1 + 1*1 + ..)
// Go through all smaller numbers
// to recursively find minimum
for (int x = 1; x <= n; x++)
{
int temp = x*x;
if (temp > n)
break;
else
res = Math.min(res, 1+getMinSquares(n - temp));
}
return res;
}
public static void main(String args[])
{
System.out.println(getMinSquares(6));
}
}
/* This code is contributed by Rajat Mishra */
Python
2029
Chapter 278. Minimum number of squares whose sum equals to given number n
C#
2030
Chapter 278. Minimum number of squares whose sum equals to given number n
PHP
<?php
// A naive recursive PHP program
// to find minimum number of
// squares whose sum is equal
// to a given number
// Returns count of minimum
// squares that sum to n
function getMinSquares($n)
{
// base cases
if ($n <= 3)
return $n;
// getMinSquares rest of the
// table using recursive formula
// Maximum squares required
// is n (1*1 + 1*1 + ..)
$res = $n;
// Go through all smaller numbers
// to recursively find minimum
for ($x = 1; $x <= $n; $x++)
{
$temp = $x * $x;
if ($temp > $n)
break;
else
$res = min($res, 1 +
getMinSquares($n -
$temp));
2031
Chapter 278. Minimum number of squares whose sum equals to given number n
}
return $res;
}
// Driver Code
echo getMinSquares(6);
// This code is contributed
// by nitin mittal.
?>
Output :
The time complexity of above solution is exponential. If we draw the complete recursion
tree, we can observer that many subproblems are solved again and again. For example,
when we start from n = 6, we can reach 4 by subtracting one 2 times and by subtracting 2
one times. So the subproblem for 4 is called twice.
Since same suproblems are called again, this problem has Overlapping Subprolems property.
So min square sum 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. Below is Dynamic Programming based solution
C++
2032
Chapter 278. Minimum number of squares whose sum equals to given number n
{
// max value is i as i can always be represented
// as 1*1 + 1*1 + ...
dp[i] = i;
// Go through all smaller numbers to
// to recursively find minimum
for (int x = 1; x <= i; x++) {
int temp = x*x;
if (temp > i)
break;
else dp[i] = min(dp[i], 1+dp[i-temp]);
}
}
// Store result and free dp[]
int res = dp[n];
delete [] dp;
return res;
}
// Driver program
int main()
{
cout << getMinSquares(6);
return 0;
}
Java
2033
Chapter 278. Minimum number of squares whose sum equals to given number n
Python
2034
Chapter 278. Minimum number of squares whose sum equals to given number n
# max value is i as i can always
# be represented as 1*1 + 1*1 + ...
dp.append(i)
# Go through all smaller numbers
# to recursively find minimum
for x in range(1, i + 1):
temp = x * x;
if temp > i:
break
else:
dp[i] = min(dp[i], 1 +
dp[i-temp])
# Store result
return dp[n]
# Driver program
print(getMinSquares(6))
# This code is contributed by nuclode
C#
2035
Chapter 278. Minimum number of squares whose sum equals to given number n
PHP
<?php
// A dynamic programming based
// PHP program to find minimum
// number of squares whose sum
// is equal to a given number
// Returns count of minimum
// squares that sum to n
function getMinSquares($n)
{
// Create a dynamic programming
2036
Chapter 278. Minimum number of squares whose sum equals to given number n
2037
Chapter 278. Minimum number of squares whose sum equals to given number n
Output:
Source
https://www.geeksforgeeks.org/minimum-number-of-squares-whose-sum-equals-to-given-number-n/
2038
Chapter 279
Approach: Sort the given elements. Using greedy approach, the best way is to remove the
minimum element or the maximum element and then check if Amax -Amin <= K. There
are various combinations of removals that have to be considered. We write a recurrence
relation to try every possible combination. There will be two possible ways of removal,
either we remove the minimum or we remove the maximum. Let(i…j) be the index of
elements left after removal of elements. Initially, we start with i=0 and j=n-1 and
the number of elements removed is 0 at the beginning. We only remove an element if
a[j]-a[i]>k, the two possible ways of removal are (i+1…j) or (i…j-1). The minimum of
the two is considered.
2039
Chapter 279. Minimum removals from array to make max – min <= K
Let DPi, j be the number of elements that need to be removed so that after removal a[j]-
a[i]<=k.
Recurrence relation for sorted array:
2040
Chapter 279. Minimum removals from array to make max – min <= K
Java
2041
Chapter 279. Minimum removals from array to make max – min <= K
// if the state has already been visited
else if (dp[i][j] != -1)
return dp[i][j];
// when Amax-Amin>d
else if ((a[j] - a[i]) > k) {
// minimum is taken of the removal
// of minimum element or removal
// of the maximum element
dp[i][j] = 1 + Math.min(countRemovals(a, i + 1, j, k),
countRemovals(a, i, j - 1, k));
}
return dp[i][j];
}
// To sort the array and return the answer
static int removals(int a[], int n, int k)
{
// sort the array
Arrays.sort(a);
// fill all stated with -1
// when only one element
for(int[] rows:dp)
Arrays.fill(rows,-1);
if (n == 1)
return 0;
else
return countRemovals(a, 0, n - 1, k);
}
// Driver code
public static void main (String[] args)
{
int a[] = { 1, 3, 4, 9, 10, 11, 12, 17, 20 };
int n = a.length;
int k = 4;
System.out.print(removals(a, n, k));
}
}
// This code is contributed by Anant Agarwal.
Python3
2042
Chapter 279. Minimum removals from array to make max – min <= K
# minimum removals to
# make max-min <= K
MAX = 100
dp = [[0 for i in range(MAX)]
for i in range(MAX)]
for i in range(0, MAX) :
for j in range(0, MAX) :
dp[i][j] = -1
# function to check all
# possible combinations
# of removal and return
# the minimum one
def countRemovals(a, i, j, k) :
global dp
# base case when all
# elements are removed
if (i >= j) :
return 0
# if condition is satisfied,
# no more removals are required
elif ((a[j] - a[i]) <= k) :
return 0
# if the state has
# already been visited
elif (dp[i][j] != -1) :
return dp[i][j]
# when Amax-Amin>d
elif ((a[j] - a[i]) > k) :
# minimum is taken of
# the removal of minimum
# element or removal of
# the maximum element
dp[i][j] = 1 + min(countRemovals(a, i + 1,
j, k),
countRemovals(a, i,
j - 1, k))
return dp[i][j]
# To sort the array
# and return the answer
def removals(a, n, k) :
2043
Chapter 279. Minimum removals from array to make max – min <= K
# sort the array
a.sort()
# fill all stated
# with -1 when only
# one element
if (n == 1) :
return 0
else :
return countRemovals(a, 0,
n - 1, k)
# Driver Code
a = [1, 3, 4, 9, 10,
11, 12, 17, 20]
n = len(a)
k = 4
print (removals(a, n, k))
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
2044
Chapter 279. Minimum removals from array to make max – min <= K
2045
Chapter 279. Minimum removals from array to make max – min <= K
{
int []a = new int[]{ 1, 3, 4, 9, 10,
11, 12, 17, 20 };
int n = a.Length;
int k = 4;
Console.Write(removals(a, n, k));
}
}
// This code is contributed by
// ManishShaw(manishshaw1)
PHP
<?php
// PHP program to find
// minimum removals to
// make max-min <= K
$MAX = 100;
$dp = array(array());
for($i = 0; $i < $MAX; $i++)
{
for($j = 0; $j < $MAX; $j++)
$dp[$i][$j] = -1;
}
// function to check all
// possible combinations
// of removal and return
// the minimum one
function countRemovals($a, $i,
$j, $k)
{
global $dp;
// base case when all
// elements are removed
if ($i >= $j)
return 0;
// if condition is satisfied,
// no more removals are required
else if (($a[$j] - $a[$i]) <= $k)
return 0;
// if the state has
// already been visited
else if ($dp[$i][$j] != -1)
2046
Chapter 279. Minimum removals from array to make max – min <= K
return $dp[$i][$j];
// when Amax-Amin>d
else if (($a[$j] - $a[$i]) > $k)
{
// minimum is taken of
// the removal of minimum
// element or removal of
// the maximum element
$dp[$i][$j] = 1 + min(countRemovals($a, $i + 1,
$j, $k),
countRemovals($a, $i,
$j - 1, $k));
}
return $dp[$i][$j];
}
// To sort the array
// and return the answer
function removals($a, $n, $k)
{
// sort the array
sort($a);
// fill all stated with -1
// when only one element
if ($n == 1)
return 0;
else
return countRemovals($a, 0,
$n - 1, $k);
}
// Driver Code
$a = array(1, 3, 4, 9, 10,
11, 12, 17, 20);
$n = count($a);
$k = 4;
echo (removals($a, $n, $k));
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output:
2047
Chapter 279. Minimum removals from array to make max – min <= K
Source
https://www.geeksforgeeks.org/minimum-removals-array-make-max-min-k/
2048
Chapter 280
Minimum splits in a binary string such that every substring is a power of 4 or 6. - Geeks-
forGeeks
Given a string S composed of 0 and 1. Find the minimum splits such that the substring is
a binary representation of the power of 4 or 6 with no leading zeros. Print -1 if no such
partitioning is possible.
Examples:
Input: 100110110
Output: 3
The string can be split into a minimum of
three substrings 100(power of 4), 110
(power of 6) and 110(power of 6).
Input : 00000
Output : -1
0 is not a power of 4 or 6.
A simple solution is to split the string recursively at different indices and check if each split
is a power of 4 or 6. Start with index 0 and split str[0] from other string. If it is a power of 4
or 6 then call recursively for index 1 and perform the same operation. When an entire string
is split check if a total number of partitions are minimum so far or not. Then split str[0..1],
check if it is the power of 4 or 6 and then call recursively for rest string. Compare partitions
with minimum so far at the end of string traversal. This approach will be exponential in
time.
2049
Chapter 280. Minimum splits in a binary string such that every substring is a power of 4
or 6.
Implementation:
C++
2050
Chapter 280. Minimum splits in a binary string such that every substring is a power of 4
or 6.
2051
Chapter 280. Minimum splits in a binary string such that every substring is a power of 4
or 6.
// Driver code
int main()
{
string binaryNo = "100110110";
cout << numberOfPartitions(binaryNo);
return 0;
}
Java
2052
Chapter 280. Minimum splits in a binary string such that every substring is a power of 4
or 6.
2053
Chapter 280. Minimum splits in a binary string such that every substring is a power of 4
or 6.
{
if (dp[j + 1] != -1)
dp[i] = Math.min(dp[i],
dp[j + 1] + 1);
}
}
}
// If no partitions are possible,
// then make dp[i] = -1 to
// represent this.
if (dp[i] == Integer.MAX_VALUE)
dp[i] = -1;
}
return dp[0];
}
// Driver code
public static void main (String[] args)
{
String binaryNo = "100110110";
System.out.println(numberOfPartitions(binaryNo));
}
}
// This code is contributed
// by shiv_bhakt.
Output: 3
Source
https://www.geeksforgeeks.org/minimum-splits-in-a-binary-string-such-that-every-substring-is-a-power-of-4-or-6/
2054
Chapter 281
Minimum steps to delete a string after repeated deletion of palindrome substrings - Geeks-
forGeeks
Given a string containing characters as integers only. We need to delete all character of this
string in a minimum number of steps where in one step we can delete the substring which
is a palindrome. After deleting a substring remaining parts are concatenated.
Examples:
Input : s = “2553432”
Output : 2
We can delete all character of above string in
2 steps, first deleting the substring s[3, 5] “343”
and then remaining string completely s[0, 3] “2552”
Input : s = “1234”
Output : 4
We can delete all character of above string in 4
steps only because each character need to be deleted
separately. No substring of length 2 is a palindrome
in above string.
We can solve this problem using Dynamic programming. Let dp[i][j] denotes the number of
steps it takes to delete the substring s[i, j]. Each character will be deleted alone or as part of
some substring so in the first case we will delete the character itself and call subproblem (i+1,
j). In the second case we will iterate over all occurrence of the current character in right side,
if K is the index of one such occurrence then the problem will reduce to two subproblems
2055
Chapter 281. Minimum steps to delete a string after repeated deletion of palindrome
substrings
(i+1, K – 1) and (K+1, j). We can reach to this subproblem (i+1, K-1) because we can just
delete the same character and call for mid substring. We need to take care of a case when
first two characters are same in that case we can directly reduce to the subproblem (i+2, j)
So after above discussion of relation among subproblems, we can write dp relation as follows,
C++
2056
Chapter 281. Minimum steps to delete a string after repeated deletion of palindrome
substrings
// if current and next char are same,
// choose min from current and subproblem
// (i+2,j)
if (str[i] == str[i + 1])
dp[i][j] = min(1 + dp[i + 2][j], dp[i][j]);
/* loop over all right characters and suppose
Kth char is same as ith character then
choose minimum from current and two
substring after ignoring ith and Kth char */
for (int K = i + 2; K <= j; K++)
if (str[i] == str[K])
dp[i][j] = min(dp[i+1][K-1] + dp[K+1][j],
dp[i][j]);
}
}
}
/* Uncomment below snippet to print actual dp tablex
for (int i = 0; i < N; i++, cout << endl)
for (int j = 0; j < N; j++)
cout << dp[i][j] << " "; */
return dp[0][N - 1];
}
// Driver code to test above methods
int main()
{
string str = "2553432";
cout << minStepToDeleteString(str) << endl;
return 0;
}
Java
2057
Chapter 281. Minimum steps to delete a string after repeated deletion of palindrome
substrings
2058
Chapter 281. Minimum steps to delete a string after repeated deletion of palindrome
substrings
C#
2059
Chapter 281. Minimum steps to delete a string after repeated deletion of palindrome
substrings
2060
Chapter 281. Minimum steps to delete a string after repeated deletion of palindrome
substrings
Output:
Source
https://www.geeksforgeeks.org/minimum-steps-to-delete-a-string-after-repeated-deletion-of-palindrome-substrings/
2061
Chapter 282
Examples:
Input : n = 10
Output : 3
Input : 6
Output : 2
while ( n > 1)
{
if (n % 3 == 0)
n /= 3;
else if (n % 2 == 0)
2062
Chapter 282. Minimum steps to minimize n as per given condition
n /= 2;
else
n--;
steps++;
}
f(n) = 1 + f(n-1)
f(n) = 1 + f(n/2) // if n is divisible by 2
f(n) = 1 + f(n/3) // if n is divisible by 3
C++
2063
Chapter 282. Minimum steps to minimize n as per given condition
memo[n] = 1 + res;
return memo[n];
}
// This function mainly initializes memo[] and
// calls getMinSteps(n, memo)
int getMinSteps(int n)
{
int memo[n+1];
// initialize memoized array
for (int i=0; i<=n; i++)
memo[i] = -1;
return getMinSteps(n, memo);
}
// driver program
int main()
{
int n = 10;
cout << getMinSteps(n);
return 0;
}
Java
2064
Chapter 282. Minimum steps to minimize n as per given condition
getMinSteps(n / 2, memo));
if (n % 3 == 0)
res = Math.min(res,
getMinSteps(n / 3, memo));
// store memo[n] and return
memo[n] = 1 + res;
return memo[n];
}
// This function mainly
// initializes memo[] and
// calls getMinSteps(n, memo)
static int getMinSteps(int n)
{
int memo[] = new int[n + 1];
// initialize memoized array
for (int i = 0; i <= n; i++)
memo[i] = -1;
return getMinSteps(n, memo);
}
// Driver Code
public static void main (String[] args)
{
int n = 10;
System.out.println(getMinSteps(n));
}
}
// This code is contributed by anuj_67.
Python3
2065
Chapter 282. Minimum steps to minimize n as per given condition
# store temp value for n as min(f(n-1),
# f(n//2), f(n//3)) + 1
res = getMinSteps(n-1, memo)
if (n%2 == 0):
res = min(res, getMinSteps(n//2, memo))
if (n%3 == 0):
res = min(res, getMinSteps(n//3, memo))
# store memo[n] and return
memo[n] = 1 + res
return memo[n]
# This function mainly
# initializes memo[] and
# calls getMinSteps(n, memo)
def getsMinSteps(n):
memo = [0 for i in range(n+1)]
# initialize memoized array
for i in range(n+1):
memo[i] = -1
return getMinSteps(n, memo)
# driver program
n = 10
print(getsMinSteps(n))
# This code is contributed by Soumen Ghosh.
C#
// C# program to minimize n to 1
// by given rule in minimum steps
using System;
class GFG {
// function to calculate min steps
static int getMinSteps(int n, int []memo)
{
// base case
if (n == 1)
return 0;
if (memo[n] != -1)
2066
Chapter 282. Minimum steps to minimize n as per given condition
return memo[n];
// store temp value for
// n as min( f(n-1),
// f(n/2), f(n/3)) +1
int res = getMinSteps(n - 1, memo);
if (n % 2 == 0)
res = Math.Min(res,
getMinSteps(n / 2, memo));
if (n % 3 == 0)
res = Math.Min(res,
getMinSteps(n / 3, memo));
// store memo[n] and return
memo[n] = 1 + res;
return memo[n];
}
// This function mainly
// initializes memo[] and
// calls getMinSteps(n, memo)
static int getMinSteps(int n)
{
int []memo = new int[n + 1];
// initialize memoized array
for (int i = 0; i <= n; i++)
memo[i] = -1;
return getMinSteps(n, memo);
}
// Driver Code
public static void Main ()
{
int n = 10;
Console.WriteLine(getMinSteps(n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to minimize n to 1 by
2067
Chapter 282. Minimum steps to minimize n as per given condition
2068
Chapter 282. Minimum steps to minimize n as per given condition
Output:
C++
Java
// A tabulation based
// solution in Java
import java.io.*;
class GFG
{
static int getMinSteps(int n)
2069
Chapter 282. Minimum steps to minimize n as per given condition
{
int table[] = new int[n + 1];
for (int i = 0; i <= n; i++)
table[i] = n - i;
for (int i = n; i >= 1; i--)
{
if (!(i % 2 > 0))
table[i / 2] = Math.min(table[i] + 1,
table[i / 2]);
if (!(i % 3 > 0))
table[i / 3] = Math.min(table[i] + 1,
table[i / 3]);
}
return table[1];
}
// Driver Code
public static void main (String[] args)
{
int n = 10;
System.out.print(getMinSteps(n));
}
}
// This code is contributed
// by anuj_67.
C#
// A tabulation based
// solution in C#
using System;
class GFG
{
static int getMinSteps(int n)
{
int []table = new int[n + 1];
for (int i = 0; i <= n; i++)
table[i] = n - i;
for (int i = n; i >= 1; i--)
{
if (!(i % 2 > 0))
table[i / 2] = Math.Min(table[i] + 1,
table[i / 2]);
if (!(i % 3 > 0))
table[i / 3] = Math.Min(table[i] + 1,
table[i / 3]);
2070
Chapter 282. Minimum steps to minimize n as per given condition
}
return table[1];
}
// Driver Code
public static void Main ()
{
int n = 10;
Console.WriteLine(getMinSteps(n));
}
}
// This code is contributed
// by anuj_67.
PHP
<?php
// A tabulation based solution in PHP
function getMinSteps( $n)
{
$table = array();
for ($i = 0; $i <= $n; $i++)
$table[$i] = $n - $i;
for ($i = $n; $i >= 1; $i--)
{
if (!($i % 2))
$table[$i / 2] = min($table[$i] +
1, $table[$i / 2]);
if (!($i % 3))
$table[$i / 3] = min($table[$i] +
1, $table[$i / 3]);
}
return $table[1];
}
// Driver Code
$n = 10;
echo getMinSteps($n);
// This code is contributed by anuj_67.
?>
Output:
2071
Chapter 282. Minimum steps to minimize n as per given condition
Improved By : vt_m
Source
https://www.geeksforgeeks.org/minimum-steps-minimize-n-per-given-condition/
2072
Chapter 283
2073
Chapter 283. Minimum steps to reach a destination
of steps INT_MAX, so that when i take the minimum of both possibilities, this one gets
eliminated.
If we don’t use this last step, the program enters into an INFINITE recursion and gives
RUN TIME ERROR.
Below is the implementation of above idea. Note that the solution only counts steps.
C++
2074
Chapter 283. Minimum steps to reach a destination
return 0;
}
Java
2075
Chapter 283. Minimum steps to reach a destination
Python3
2076
Chapter 283. Minimum steps to reach a destination
# This code is contributed by Sam007.
C#
2077
Chapter 283. Minimum steps to reach a destination
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to count number
// of steps to reach a point
// Function to count number
// of steps required to reach
// a destination
// source -> source vertex
// step -> value of last step taken
// dest -> destination vertex
function steps($source, $step, $dest)
{
// base cases
if (abs($source) > ($dest))
return PHP_INT_MAX;
if ($source == $dest)
return $step;
// at each point we
// can go either way
// if we go on positive side
$pos = steps($source + $step + 1,
$step + 1, $dest);
// if we go on negative side
$neg = steps($source - $step - 1,
$step + 1, $dest);
// minimum of both cases
return min($pos, $neg);
}
// Driver code
$dest = 11;
echo "No. of steps required to reach ",
$dest, " is ", steps(0, 0, $dest);
// This code is contributed by aj_36
?>
2078
Chapter 283. Minimum steps to reach a destination
Output :
Source
https://www.geeksforgeeks.org/minimum-steps-to-reach-a-destination/
2079
Chapter 284
Examples :
2080
Chapter 284. Minimum steps to reach target by a Knight | Set 2
A BFS approach to solve the above problem has already been discussed in the previous post.
In this a post, a Dynamic Programming solution is discussed.
Explanation of the approach :
• Case 1 : If target is not along one row or one column of knight’s position.
Let a chess board of 8 x 8 cell. Now, let say knight is at (3, 3) and the target is at
(7, 8). There are possible 8 moves from the current position of knight i.e. (2, 1), (1,
2), (4, 1), (1, 4), (5, 2), (2, 5), (5, 4), (4, 5). But, among these only two moves (5,
4) and (4, 5) will be towards the target and all other goes away from the target. So,
for finding minimum steps go to either (4, 5) or (5, 4). Now, calculate the minimum
steps taken from (4, 5) and (5, 4) to reach the target. This is calculated by dynamic
programming. Thus, this results in the minimum steps from (3, 3) to (7, 8).
• Case 2 : If the target is along one row or one column of knight’s position.
Let a chess board of 8 x 8 cell. Now, let’s say knight is at (4, 3) and the target is at
(4, 7). There are possible 8 moves but towards the target, there are only 4 moves i.e.
(5, 5), (3, 5), (2, 4), (6, 4). As, (5, 5) is equivalent to (3, 5) and (2, 4) is equivalent
to (6, 4). So, from these 4 points, it can be converted into 2 points. Taking (5, 5)
and (6, 4) (here). Now, calculate the minimum steps taken from these two points to
reach the target. This is calculated by dynamic programming. Thus, this results in
the minimum steps from (4, 3) to (4, 7).
Exception : When the knight will be at corner and the target is such that the difference
of x and y coordinates with knight’s position is (1, 1) or vice-versa. Then minimum steps
will be 4.
Dynamic Programming Equation :
2081
Chapter 284. Minimum steps to reach target by a Knight | Set 2
2082
Chapter 284. Minimum steps to reach target by a Knight | Set 2
y1 = y - 1;
x2 = x - 1;
y2 = y - 2;
}
}
// ans will be, 1 + minimum of steps
// required from (x1, y1) and (x2, y2).
dp[abs(x - tx)][abs(y - ty)] =
min(getsteps(x1, y1, tx, ty),
getsteps(x2, y2, tx, ty)) + 1;
// exchanging the coordinates x with y of both
// knight and target will result in same ans.
dp[abs(y - ty)][abs(x - tx)] =
dp[abs(x - tx)][abs(y - ty)];
return dp[abs(x - tx)][abs(y - ty)];
}
}
}
// Driver Code
int main()
{
int i, n, x, y, tx, ty, ans;
// size of chess board n*n
n = 100;
// (x, y) coordinate of the knight.
// (tx, ty) coordinate of the target position.
x = 4;
y = 5;
tx = 1;
ty = 1;
// (Exception) these are the four corner points
// for which the minimum steps is 4.
if ((x == 1 && y == 1 && tx == 2 && ty == 2) ||
(x == 2 && y == 2 && tx == 1 && ty == 1))
ans = 4;
else if ((x == 1 && y == n && tx == 2 && ty == n - 1) ||
(x == 2 && y == n - 1 && tx == 1 && ty == n))
ans = 4;
else if ((x == n && y == 1 && tx == n - 1 && ty == 2) ||
(x == n - 1 && y == 2 && tx == n && ty == 1))
ans = 4;
else if ((x == n && y == n && tx == n - 1 && ty == n - 1) ||
2083
Chapter 284. Minimum steps to reach target by a Knight | Set 2
Output:
Source
https://www.geeksforgeeks.org/minimum-steps-reach-target-knight-set-2/
2084
Chapter 285
Minimum sum of
multiplications of n numbers
Input : 40 60 20
Output : 2400
Explanation: There are two possible cases:
1st possibility: Take 40 and 60, so multiplication=2400
and put back (60+40) % 100 = 0, making it 0, 20.
Multiplying 0 and 20 we get 0 so
multiplication = 2400+0 = 2400. Put back (0+20)%100 = 20.
2nd possibility: take 60 and 20, so 60*20 = 1200,
put back (60+20)%100 = 80, making it [40, 80]
multiply 40*80 to get 3200, so multiplication
sum = 1200+3200 = 4400. Put back (40+80)%100 = 20
Input : 5 6
Output : 30
Explanation: Only possibility is 5*6=30
2085
Chapter 285. Minimum sum of multiplications of n numbers
into k parts, for every DPi,j we will have k partitions i<=k<j , store the minimum of them.
So we get the formula similar to Matrix chain Multiplication Dynamic Programming.
Since many subproblems will be repeating, hence we use memoization to store the values in
a nXn matrix.
Given below is the illustration of the above approach:
C++
2086
Chapter 285. Minimum sum of multiplications of n numbers
dp[i][j] = INT_MAX;
// we break them into k partitions
for (int k = i; k < j; k++)
{
// store the min of the
// formula thus obtained
dp[i][j] = min(dp[i][j], (solve(a, i, k) +
solve(a, k + 1, j) +
(sum(a, i, k) * sum(a, k + 1, j))));
}
// return the minimum
return dp[i][j];
}
void intialize(int n)
{
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++)
dp[i][j] = -1;
}
// Driver code
int main() {
int a[] = {40, 60, 20};
int n = sizeof(a) / sizeof(a[0]);
intialize(n);
cout << solve(a, 0, n - 1) << endl;
return 0;
}
Java
2087
Chapter 285. Minimum sum of multiplications of n numbers
2088
Chapter 285. Minimum sum of multiplications of n numbers
{
int a[] = {40, 60, 20};
int n = a.length;
intialize(n);
System.out.println(solve(a, 0, n - 1));
}
}
/*This code is contributed by Nikita Tiwari.*/
C#
2089
Chapter 285. Minimum sum of multiplications of n numbers
dp[i, j] = 100000000;
// we break them into k partitions
for (int k = i; k < j; k++)
{
// store the min of the
// formula thus obtained
dp[i, j] = Math.Min(dp[i, j], (solve(a, i, k) +
solve(a, k + 1, j) +
(sum(a, i, k) * sum(a, k + 1, j))));
}
// return the minimum
return dp[i, j];
}
static void intialize(int n)
{
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++)
dp[i, j] = -1;
}
// Driver code
public static void Main()
{
int []a = {40, 60, 20};
int n = a.Length;
intialize(n);
Console.WriteLine(solve(a, 0, n - 1));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find the
// minimum sum of multiplication
// of n numbers
// Used in recursive
// memoized solution
$dp = array(array());
2090
Chapter 285. Minimum sum of multiplications of n numbers
2091
Chapter 285. Minimum sum of multiplications of n numbers
$dp[$i][$j] = -1;
}
// Driver code
$a = array(40, 60, 20);
$n = count($a);
intialize($n);
echo solve($a, 0, $n - 1) ;
// This code is contributed by anuj_67.
?>
Output :
2400
Source
https://www.geeksforgeeks.org/minimum-sum-of-multiplications-of-n-numbers/
2092
Chapter 286
Method 1 (Naive Approach): Check every possible submatrix in given 2D array. This
solution requires 4 nested loops and time complexity of this solution would be O(n^4).
Method 2 (Efficient Approach): Kadane’s algorithm for 1D array can be used to
reduce the time complexity to O(n^3). The idea is to fix the left and right columns one by
one and find the minimum sum contiguous rows for every left and right column pair. We
basically find top and bottom row numbers (which have minimum sum) for every fixed left
and right column pair. To find the top and bottom row numbers, calculate sun of elements in
every row from left to right and store these sums in an array say temp[]. So temp[i] indicates
sum of elements from left to right in row i. If we apply Kadane’s 1D algorithm on temp[],
and get the minimum sum subarray of temp, this minimum sum would be the minimum
possible sum with left and right as boundary columns. To get the overall minimum sum,
we compare this sum with the minimum sum so far.
2093
Chapter 286. Minimum sum submatrix in a given 2D array
2094
Chapter 286. Minimum sum submatrix in a given 2D array
2095
Chapter 286. Minimum sum submatrix in a given 2D array
Output:
Source
https://www.geeksforgeeks.org/minimum-sum-submatrix-given-2d-array/
2096
Chapter 287
Minimum sum subsequence such that at least one of every four consecutive elements is
picked - GeeksforGeeks
Given an array arr[] of positive integers. The task is to find minimum sum subsequence
from the array such that at least one value among all groups of four consecutive elements
is picked.
Examples :
2097
Chapter 287. Minimum sum subsequence such that at least one of every four consecutive
elements is picked
second three.
The idea is similar to LIS problem. We store minimum sum subsequence ending with every
element of arr[]. We finally return minimum of last four values.
2098
Chapter 287. Minimum sum subsequence such that at least one of every four consecutive
elements is picked
int dp[n];
// If there is single value, we get the
// minimum sum equal to arr[0]
if (n == 1)
return arr[0];
// If there are two values, we get the
// minimum sum equal to the minimum of
// two values
if (n == 2)
return min(arr[0], arr[1]);
// If there are three values, return
// minimum of the three elements of
// array
if (n == 3)
return min(arr[0], min(arr[1], arr[2]));
// If there are four values, return minimum
// of the four elements of array
if (n == 4)
return min(min(arr[0], arr[1]),
min(arr[2], arr[3]));
dp[0] = arr[0];
dp[1] = arr[1];
dp[2] = arr[2];
dp[3] = arr[3];
for (int i = 4; i < n; i++)
dp[i] = arr[i] + min(min(dp[i - 1], dp[i - 2]),
min(dp[i - 3], dp[i - 4]));
// Return the minimum of last 4 index
return min(min(dp[n - 1], dp[n - 2]),
min(dp[n - 4], dp[n - 3]));
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 3, 4, 5, 6, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << minSum(arr, n);
return 0;
}
2099
Chapter 287. Minimum sum subsequence such that at least one of every four consecutive
elements is picked
Java
2100
Chapter 287. Minimum sum subsequence such that at least one of every four consecutive
elements is picked
for (int i = 4; i < n; i++)
dp[i] = arr[i] + Math.min(Math.min(dp[i - 1], dp[i - 2]),
Math.min(dp[i - 3], dp[i - 4]));
// Return the minimum of last 4 index
return Math.min(Math.min(dp[n - 1], dp[n - 2]),
Math.min(dp[n - 4], dp[n - 3]));
}
// Driver code
static public void main(String[] args)
{
int[] arr = { 1, 2, 3, 3, 4, 5, 6, 1 };
int n = arr.length;
System.out.println(minSum(arr, n));
}
}
// This Code is contributed by vt_m.
C#
2101
Chapter 287. Minimum sum subsequence such that at least one of every four consecutive
elements is picked
Output:
Alternate Solution :
2102
Chapter 287. Minimum sum subsequence such that at least one of every four consecutive
elements is picked
First of all, think that we have only four elements then our result is at least four given
elements. Now, in the case if we have more than four elements then we must maintain an
array sum[] where sum[i] includes the possible minimal sum up to i-th element and also i-th
element must be a part of the solution.
While computing sum[i], our base condition is that arr[i] must be a part of sum[i] and then we
must have an element from last four elements. So, we can recursively compute sum[i] as sum
of arr[i] and minimum (sum[i-1], sum[i-2], sum[i-3], sum[i-4]). Since there are overlapping
sub problems in recursive structure of our problem, we can use Dynamic Programming to
solve this problem. And for final result we must compute minimum of last four values of
sum[] array as result must contain an element from last four elements.
2103
Chapter 287. Minimum sum subsequence such that at least one of every four consecutive
elements is picked
Output:
Source
https://www.geeksforgeeks.org/minimum-sum-subsequence-least-one-every-four-consecutive-elements-picked/
2104
Chapter 288
Examples :
2105
Chapter 288. Minimum time to finish tasks without skipping two consecutive
Let minTime(i) be minimum time to finish till i’th task. It can be written as minimum of
two values.
1. Minimum time if i’th task is included in list, let this time be incl(i)
2. Minimum time if i’th task is excluded from result, let this time be excl(i)
A simple solution is to make two tables incl[] and excl[] to store times for tasks. Finally
return minimum of incl[n-1] and excl[n-1]. This solution requires O(n) time and O(n) space.
If we take a closer look, we can notice that we only need incl and excl of previous job.
So we can save space and solve the problem in O(n) time and O(1) space. Below is C++
implementation of the idea.
C++
2106
Chapter 288. Minimum time to finish tasks without skipping two consecutive
2107
Chapter 288. Minimum time to finish tasks without skipping two consecutive
Java
2108
Chapter 288. Minimum time to finish tasks without skipping two consecutive
excl = excl_new;
}
// Return maximum of two values for
// last task
return Math.min(incl, excl);
}
// Driver code
public static void main(String[] args)
{
int arr1[] = {10, 5, 2, 7, 10};
int n1 = arr1.length;
System.out.println(minTime(arr1, n1));
int arr2[] = {10, 5, 7, 10};
int n2 = arr2.length;
System.out.println(minTime(arr2, n2));
int arr3[] = {10, 5, 2, 4, 8, 6, 7, 10};
int n3 = arr3.length;
System.out.println(minTime(arr3, n3));
}
}
// This code is contributed by Prerna Saini
Python3
# Python3 program to find minimum
# time to finish tasks such that no
# two consecutive tasks are skipped.
# arr[] represents time
# taken by n given tasks
def minTime(arr, n):
# Corner Cases
if (n <= 0): return 0
# Initialize value for the
# case when there is only
# one task in task list.
incl = arr[0] # First task is included
excl = 0 # First task is exluded
# Process remaining n-1 tasks
2109
Chapter 288. Minimum time to finish tasks without skipping two consecutive
C#
2110
Chapter 288. Minimum time to finish tasks without skipping two consecutive
{
// Corner Cases
if (n <= 0)
return 0;
// Initialize value for the case
// when there is only one task in
// task list.
// First task is included
int incl = arr[0];
// First task is exluded
int excl = 0;
// Process remaining n-1 tasks
for (int i = 1; i < n; i++)
{
// Time taken if current task is
// included. There are two
// possibilities
// (a) Previous task is also included
// (b) Previous task is not included
int incl_new = arr[i] + Math.Min(excl,
incl);
// Time taken when current task is not
// included. There is only one
// possibility that previous task is
// also included.
int excl_new = incl;
// Update incl and excl for next
// iteration
incl = incl_new;
excl = excl_new;
}
// Return maximum of two values for
// last task
return Math.Min(incl, excl);
}
// Driver code
public static void Main()
{
int []arr1 = {10, 5, 2, 7, 10};
int n1 = arr1.Length;
Console.WriteLine(minTime(arr1, n1));
2111
Chapter 288. Minimum time to finish tasks without skipping two consecutive
int []arr2 = {10, 5, 7, 10};
int n2 = arr2.Length;
Console.WriteLine(minTime(arr2, n2));
int []arr3 = {10, 5, 2, 4, 8, 6, 7, 10};
int n3 = arr3.Length;
Console.WriteLine(minTime(arr3, n3));
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// PHP program to find minimum time
// to finish tasks such that no two
// consecutive tasks are skipped.
// arr[] represents time
// taken by n given tasks
function minTime($arr, $n)
{
// Corner Cases
if ($n <= 0)
return 0;
// Initialize value for the
// case when there is only
// one task in task list.
// First task is included
$incl = $arr[0];
// First task is exluded
$excl = 0;
// Process remaining n-1 tasks
for ($i = 1; $i < $n; $i++)
{
// Time taken if current task is
// included There are two possibilities
// (a) Previous task is also included
// (b) Previous task is not included
$incl_new = $arr[$i] + min($excl, $incl);
// Time taken when current task
2112
Chapter 288. Minimum time to finish tasks without skipping two consecutive
Output :
12
12
22
Related Problems:
Find minimum time to finish all jobs with given constraints
Maximum sum such that no two elements are adjacent.
Improved By : nitin mittal
2113
Chapter 288. Minimum time to finish tasks without skipping two consecutive
Source
https://www.geeksforgeeks.org/minimum-time-to-finish-tasks-without-skipping-two-consecutive/
2114
Chapter 289
Minimum time to write characters using insert, delete and copy operation - GeeksforGeeks
We need to write N same characters on a screen and each time we can insert a character,
delete the last character and copy and paste all written characters i.e. after copy operation
count of total written character will become twice. Now we are given time for insertion,
deletion and copying. We need to output minimum time to write N characters on the screen
using these operations.
Examples:
Input : N = 9
insert time = 1
removal time = 2
copy time = 1
Output : 5
N character can be written on screen in 5 time units as shown below,
insert a character
characters = 1 total time = 1
again insert character
characters = 2 total time = 2
copy characters
characters = 4 total time = 3
copy characters
characters = 8 total time = 4
insert character
characters = 9 total time = 5
2115
Chapter 289. Minimum time to write characters using insert, delete and copy operation
We can solve this problem using dynamic programming. We can observe a pattern after
solving some examples by hand that for writing each character we have two choices either
get it by inserting or get it by copying, whichever takes less time. Now writing relation
accordingly,
Let dp[i] be the optimal time to write i characters on screen then,
If i is even then,
dp[i] = min((dp[i-1] + insert_time),
(dp[i/2] + copy_time))
Else (If i is odd)
dp[i] = min(dp[i-1] + insert_time),
(dp[(i+1)/2] + copy_time + removal_time)
In the case of odd, removal time is added because when (i+1)/2 characters will be copied
one extra character will be on the screen which needs to be removed. Total time complexity
of solution will be O(N) and auxiliary space needed will be O(N).
2116
Chapter 289. Minimum time to write characters using insert, delete and copy operation
Output:
Source
https://www.geeksforgeeks.org/minimum-time-write-characters-using-insert-delete-copy-operation/
2117
Chapter 290
Given a number N, find out the number of possible numbers of given length.
Examples:
For N=1, number of possible numbers would be 10 (0, 1, 2, 3, …., 9)
For N=2, number of possible numbers would be 36
Possible numbers: 00,08 11,12,14 22,21,23,25 and so on.
If we start with 0, valid numbers will be 00, 08 (count: 2)
If we start with 1, valid numbers will be 11, 12, 14 (count: 3)
If we start with 2, valid numbers will be 22, 21, 23,25 (count: 4)
If we start with 3, valid numbers will be 33, 32, 36 (count: 3)
If we start with 4, valid numbers will be 44,41,45,47 (count: 4)
If we start with 5, valid numbers will be 55,54,52,56,58 (count: 5)
………………………………
2118
Chapter 290. Mobile Numeric Keypad Problem
………………………………
We need to print the count of possible numbers.
N = 1 is trivial case, number of possible numbers would be 10 (0, 1, 2, 3, …., 9)
For N > 1, we need to start from some button, then move to any of the four direction (up,
left, right or down) which takes to a valid button (should not go to *, #). Keep doing this
until N length number is obtained (depth first traversal).
Recursive Solution:
Mobile Keypad is a rectangular grid of 4X3 (4 rows and 3 columns)
Lets say Count(i, j, N) represents the count of N length numbers starting from position (i,
j)
If N = 1
Count(i, j, N) = 10
Else
Count(i, j, N) = Sum of all Count(r, c, N-1) where (r, c) is new
position after valid move of length 1 from current
position (i, j)
2119
Chapter 290. Mobile Numeric Keypad Problem
{
ro = i + row[move];
co = j + col[move];
if (ro >= 0 && ro <= 3 && co >=0 && co <= 2 &&
keypad[ro][co] != '*' && keypad[ro][co] != '#')
{
totalCount += getCountUtil(keypad, ro, co, n-1);
}
}
return totalCount;
}
// Return count of all possible numbers of length n
// in a given numeric keyboard
int getCount(char keypad[][3], int n)
{
// Base cases
if (keypad == NULL || n <= 0)
return 0;
if (n == 1)
return 10;
int i=0, j=0, totalCount = 0;
for (i=0; i<4; i++) // Loop on keypad row
{
for (j=0; j<3; j++) // Loop on keypad column
{
// Process for 0 to 9 digits
if (keypad[i][j] != '*' && keypad[i][j] != '#')
{
// Get count when number is starting from key
// position (i, j) and add in count obtained so far
totalCount += getCountUtil(keypad, i, j, n);
}
}
}
return totalCount;
}
// Driver program to test above function
int main(int argc, char *argv[])
{
char keypad[4][3] = {{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}};
printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));
2120
Chapter 290. Mobile Numeric Keypad Problem
Output:
Dynamic Programming
There are many repeated traversal on smaller paths (traversal for smaller N) to find all
possible longer paths (traversal for bigger N). See following two diagrams for example. In
this traversal, for N = 4 from two starting positions (buttons ‘4’ and ‘8’), we can see there
are few repeated traversals for N = 2 (e.g. 4 -> 1, 6 -> 3, 8 -> 9, 8 -> 7 etc).
2121
Chapter 290. Mobile Numeric Keypad Problem
Since the problem has both properties: Optimal Substructure and Overlapping Subproblems,
it can be efficiently solved using dynamic programming.
Following is C program for dynamic programming implementation.
2122
Chapter 290. Mobile Numeric Keypad Problem
count[i][0] = 0;
count[i][1] = 1;
}
// Bottom up - Get number count of length 2, 3, 4, ... , n
for (k=2; k<=n; k++)
{
for (i=0; i<4; i++) // Loop on keypad row
{
for (j=0; j<3; j++) // Loop on keypad column
{
// Process for 0 to 9 digits
if (keypad[i][j] != '*' && keypad[i][j] != '#')
{
// Here we are counting the numbers starting with
// digit keypad[i][j] and of length k keypad[i][j]
// will become 1st digit, and we need to look for
// (k-1) more digits
num = keypad[i][j] - '0';
count[num][k] = 0;
// move left, up, right, down from current location
// and if new location is valid, then get number
// count of length (k-1) from that new digit and
// add in count we found so far
for (move=0; move<5; move++)
{
ro = i + row[move];
co = j + col[move];
if (ro >= 0 && ro <= 3 && co >=0 && co <= 2 &&
keypad[ro][co] != '*' && keypad[ro][co] != '#')
{
nextNum = keypad[ro][co] - '0';
count[num][k] += count[nextNum][k-1];
}
}
}
}
}
}
// Get count of all possible numbers of length "n" starting
// with digit 0, 1, 2, ..., 9
totalCount = 0;
for (i=0; i<=9; i++)
totalCount += count[i][n];
return totalCount;
}
2123
Chapter 290. Mobile Numeric Keypad Problem
// Driver program to test above function
int main(int argc, char *argv[])
{
char keypad[4][3] = {{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}};
printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));
printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2));
printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3));
printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4));
printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5));
return 0;
}
Output:
2124
Chapter 290. Mobile Numeric Keypad Problem
2125
Chapter 290. Mobile Numeric Keypad Problem
}
else
{
for (i=0; i<=9; i++)
totalCount += odd[i];
}
return totalCount;
}
// Driver program to test above function
int main()
{
char keypad[4][3] = {{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));
printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2));
printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3));
printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4));
printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5));
return 0;
}
Output:
This article is contributed by Anurag Singh. 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/mobile-numeric-keypad-problem/
2126
Chapter 291
This problem is a variation of Assembly Line Scheduling and can be solved using dynamic
programming. We need to maximize sum of differences each value X should be changed to
either 1 or X. To achieve above stated condition we take a dp array of array length size
with 2 columns, where dp[i][0] stores the maximum value of sum using first i elements only
if ith array value is modified to 1 and dp[i][1] stores the maximum value of sum using first
i elements if ith array value is kept as a[i] itself.Main thing to observe is,
C++
2127
Chapter 291. Modify array to maximize sum of adjacent differences
// difference sum
#include <bits/stdc++.h>
using namespace std;
// Returns maximum-difference-sum with array
// modifications allowed.
int maximumDifferenceSum(int arr[], int N)
{
// Initialize dp[][] with 0 values.
int dp[N][2];
for (int i = 0; i < N; i++)
dp[i][0] = dp[i][1] = 0;
for (int i=0; i<(N-1); i++)
{
/* for [i+1][0] (i.e. current modified
value is 1), choose maximum from
dp[i][0] + abs(1 - 1) = dp[i][0] and
dp[i][1] + abs(1 - arr[i]) */
dp[i + 1][0] = max(dp[i][0],
dp[i][1] + abs(1-arr[i]));
/* for [i+1][1] (i.e. current modified value
is arr[i+1]), choose maximum from
dp[i][0] + abs(arr[i+1] - 1) and
dp[i][1] + abs(arr[i+1] - arr[i])*/
dp[i + 1][1] = max(dp[i][0] + abs(arr[i+1] - 1),
dp[i][1] + abs(arr[i+1] - arr[i]));
}
return max(dp[N-1][0], dp[N-1][1]);
}
// Driver code to test above methods
int main()
{
int arr[] = {3, 2, 1, 4, 5};
int N = sizeof(arr) / sizeof(arr[0]);
cout << maximumDifferenceSum(arr, N) << endl;
return 0;
}
Java
2128
Chapter 291. Modify array to maximize sum of adjacent differences
class GFG
{
// Returns maximum-difference-sum with array
// modifications allowed.
static int maximumDifferenceSum(int arr[], int N)
{
// Initialize dp[][] with 0 values.
int dp[][] = new int [N][2];
for (int i = 0; i < N; i++)
dp[i][0] = dp[i][1] = 0;
for (int i = 0; i< (N - 1); i++)
{
/* for [i+1][0] (i.e. current modified
value is 1), choose maximum from
dp[i][0] + abs(1 - 1) = dp[i][0] and
dp[i][1] + abs(1 - arr[i]) */
dp[i + 1][0] = Math.max(dp[i][0],
dp[i][1] + Math.abs(1 - arr[i]));
/* for [i+1][1] (i.e. current modified value
is arr[i+1]), choose maximum from
dp[i][0] + abs(arr[i+1] - 1) and
dp[i][1] + abs(arr[i+1] - arr[i])*/
dp[i + 1][1] = Math.max(dp[i][0] +
Math.abs(arr[i + 1] - 1),
dp[i][1] + Math.abs(arr[i + 1]
- arr[i]));
}
return Math.max(dp[N - 1][0], dp[N - 1][1]);
}
// Driver code
public static void main (String[] args)
{
int arr[] = {3, 2, 1, 4, 5};
int N = arr.length;
System.out.println( maximumDifferenceSum(arr, N));
}
}
// This code is contributed by vt_m
C#
2129
Chapter 291. Modify array to maximize sum of adjacent differences
2130
Chapter 291. Modify array to maximize sum of adjacent differences
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to get maximum
// consecutive element
// difference sum
// Returns maximum-difference-sum
// with array modifications allowed.
function maximumDifferenceSum($arr, $N)
{
// Initialize dp[][]
// with 0 values.
$dp = array(array());
for ($i = 0; $i < $N; $i++)
$dp[$i][0] = $dp[$i][1] = 0;
for ($i = 0; $i < ($N - 1); $i++)
{
/* for [i+1][0] (i.e. current
modified value is 1), choose
maximum from dp[$i][0] +
abs(1 - 1) = dp[i][0] and
dp[$i][1] + abs(1 - arr[i]) */
$dp[$i + 1][0] = max($dp[$i][0],
$dp[$i][1] +
abs(1 - $arr[$i]));
/* for [i+1][1] (i.e. current
modified value is arr[i+1]),
choose maximum from dp[i][0] +
abs(arr[i+1] - 1) and dp[i][1] +
abs(arr[i+1] - arr[i])*/
$dp[$i + 1][1] = max($dp[$i][0] +
abs($arr[$i + 1] - 1),
$dp[$i][1] +
abs($arr[$i + 1] -
$arr[$i]));
}
return max($dp[$N - 1][0], $dp[$N - 1][1]);
}
// Driver Code
$arr = array(3, 2, 1, 4, 5);
2131
Chapter 291. Modify array to maximize sum of adjacent differences
$N = count($arr);
echo maximumDifferenceSum($arr, $N);
// This code is contributed by anuj_67.
?>
Output :
Source
https://www.geeksforgeeks.org/modify-array-to-maximize-sum-of-adjacent-differences/
2132
Chapter 292
Input : 5
Output : 0 1 4 5 16
Input : 10
Output : 0 1 4 5 16 17 20 21 64 65
It is observed that the terms of the sequence follow the recurrence relation :
1) S(2 * n) = 4 * S(n)
2) S(2 * n + 1) = 4 * S(n) + 1
with S(0) = 0 and S(1) = 1
It may be noted here that any number which is the sum of non-distinct powers of 4 are not
a part of the sequence. For example, 8 is not a part of the sequence because it is formed as
the sum of non-distinct powers of 4, that are 4 and 4.
Thus, any number which is not a power of 4 and is present in the sequence must be the sum
of the distinct powers of 4.
For example, 21 is a part of the sequence, even though it is not a power of 4 because it is
the sum of the distinct powers of 4, that are 1, 4 and 16.
Employ the recurrence relation discussed above to generate the sequence, efficiently.
C++
2133
Chapter 292. Moser-de Bruijn Sequence
// CPP code to generate first 'n' terms
// of the Moser-de Bruijn Sequence
#include <bits/stdc++.h>
using namespace std;
// Function to generate nth term
// of Moser-de Bruijn Sequence
int gen(int n)
{
// S(0) = 0
if (n == 0)
return 0;
// S(1) = 1
else if (n == 1)
return 1;
// S(2 * n) = 4 * S(n)
else if (n % 2 == 0)
return 4 * gen(n / 2);
// S(2 * n + 1) = 4 * S(n) + 1
else if (n % 2 == 1)
return 4 * gen(n / 2) + 1;
}
// Generating the first 'n' terms
// of Moser-de Bruijn Sequence
void moserDeBruijn(int n)
{
for (int i = 0; i < n; i++)
cout << gen(i) << " ";
cout << "\n";
}
// Driver Code
int main()
{
int n = 15;
cout << "First " << n << " terms of "
<< "Moser-de Bruijn Sequence : \n";
moserDeBruijn(n);
return 0;
}
Java
2134
Chapter 292. Moser-de Bruijn Sequence
2135
Chapter 292. Moser-de Bruijn Sequence
// This code is contributed by JaideepPyne.
Python3
C#
2136
Chapter 292. Moser-de Bruijn Sequence
using System;
class GFG {
// Function to generate nth term
// of Moser-de Bruijn Sequence
public static int gen(int n)
{
// S(0) = 0
if (n == 0)
return 0;
// S(1) = 1
else if (n == 1)
return 1;
// S(2 * n) = 4 * S(n)
else if (n % 2 == 0)
return 4 * gen(n / 2);
// S(2 * n + 1) = 4 * S(n) + 1
else if (n % 2 == 1)
return 4 * gen(n / 2) + 1;
return 0;
}
// Generating the first 'n' terms
// of Moser-de Bruijn Sequence
public static void moserDeBruijn(int n)
{
for (int i = 0; i < n; i++)
Console.Write(gen(i) + " ");
Console.WriteLine();
}
// Driver Code
public static void Main()
{
int n = 15;
Console.WriteLine("First " + n +
" terms of " +
"Moser-de Bruijn Sequence : ");
moserDeBruijn(n);
}
}
// This code is contributed by anuj_67.
2137
Chapter 292. Moser-de Bruijn Sequence
PHP
<?php
// PHP code to generate first 'n' terms
// of the Moser-de Bruijn Sequence
// Function to generate nth term
// of Moser-de Bruijn Sequence
function gen($n)
{
// S(0) = 0
if ($n == 0)
return 0;
// S(1) = 1
else if ($n == 1)
return 1;
// S(2 * n) = 4 * S(n)
else if ($n % 2 == 0)
return 4 * gen($n / 2);
// S(2 * n + 1) = 4 * S(n) + 1
else if ($n % 2 == 1)
return 4 * gen($n / 2) + 1;
}
// Generating the first 'n' terms
// of Moser-de Bruijn Sequence
function moserDeBruijn($n)
{
for ($i = 0; $i < $n; $i++)
echo(gen($i) . " ");
echo("\n");
}
// Driver Code
$n = 15;
echo("First " . $n . " terms of " .
"Moser-de Bruijn Sequence : \n");
echo(moserDeBruijn($n));
// This code is contributed by Ajit.
?>
Output :
2138
Chapter 292. Moser-de Bruijn Sequence
C++
2139
Chapter 292. Moser-de Bruijn Sequence
{
int n = 15;
cout << "First " << n << " terms of "
<< "Moser-de Bruijn Sequence : \n";
moserDeBruijn(n);
return 0;
}
Java
2140
Chapter 292. Moser-de Bruijn Sequence
// Driver Code
public static void main(String[] args)
{
int n = 15;
System.out.println("First " + n +
" terms of " +
"Moser-de Bruijn Sequence : ");
moserDeBruijn(n);
}
}
// This code is contributed by
// Smitha Dinesh Semwal.
python3
2141
Chapter 292. Moser-de Bruijn Sequence
C#
2142
Chapter 292. Moser-de Bruijn Sequence
Console.WriteLine("First " + n +
" terms of " +
"Moser-de Bruijn Sequence : ");
moserDeBruijn(n);
}
}
// This code is contributed by
// Smitha Dinesh Semwal.
PHP
<?php
// PHP code to generate first 'n' terms
// of the Moser-de Bruijn Sequence
// Function to generate nth term
// of Moser-de Bruijn Sequence
function gen( $n)
{
$S = array();
$S[0] = 0;
$S[1] = 1;
for ( $i = 2; $i <= $n; $i++)
{
// S(2 * n) = 4 * S(n)
if ($i % 2 == 0)
$S[$i] = 4 * $S[$i / 2];
// S(2 * n + 1) = 4 * S(n) + 1
else
$S[$i] = 4 * $S[$i/2] + 1;
}
return $S[$n];
}
// Generating the first 'n' terms
// of Moser-de Bruijn Sequence
function moserDeBruijn( $n)
{
for ( $i = 0; $i < $n; $i++)
echo gen($i) , " ";
echo "\n";
}
2143
Chapter 292. Moser-de Bruijn Sequence
// Driver Code
$n = 15;
echo "First " ,$n ," terms of "
, "Moser-de Bruijn Sequence : \n";
moserDeBruijn($n);
// This code is contributed by anuj_67.
?>
Output :
Source
https://www.geeksforgeeks.org/moser-de-bruijn-sequence/
2144
Chapter 293
2145
Chapter 293. Multistage Graph (Shortest Path)
• The Brute force method of finding all possible paths between Source and Destination
and then finding the minimum. That’s the WORST possible strategy.
• Dijkstra’s Algorithm of Single Source shortest paths. This method will find shortest
paths from source to all other nodes which is not required in this case. So it will take
a lot of time and it doesn’t even use the SPECIAL feature that this MULTI-STAGE
graph has.
• Simple Greedy Method – At each node, choose the shortest outgoing path. If we
apply this approach to the example graph give above we get the solution as 1 + 4 +
18 = 23. But a quick look at the graph will show much shorter paths available than
23. So the greedy method fails !
• The best option is Dynamic Programming. So we need to find Optimal Sub-
structure, Recursive Equations and Overlapping Sub-problems.
We define the notation :- M(x, y) as the minimum cost to T(target node) from Stage x,
Node y.
// From 0, we can go to 1 or 2 or 3 to
// reach 7.
M(1, 0) = min(1 + M(2, 1),
2 + M(2, 2),
5 + M(2, 3))
This means that our problem of 0 —> 7 is now sub-divided into 3 sub-problems :-
M(1, 0)
/ | \
/ | \
M(2, 1) M(2, 2) M(2, 3)
2146
Chapter 293. Multistage Graph (Shortest Path)
/ \ / \ / \
M(3, 4) M(3, 5) M(3, 4) M(3, 5) M(3, 6) M(3, 6)
. . . . . .
. . . . . .
. . . . . .
So, here we have drawn a very small part of the Recursion Tree and we can already see
Overlapping Sub-Problems. We can largely reduce the number of M(x, y) evaluations using
Dynamic Programming.
Implementation details:
The below implementation assumes that nodes are numbered from 0 to N-1 from first stage
(source) to last stage (destination). We also assume that the input graph is multistage.
2147
Chapter 293. Multistage Graph (Shortest Path)
continue;
// We apply recursive equation to
// distance to target through j.
// and compare with minimum distance
// so far.
dist[i] = min(dist[i], graph[i][j] +
dist[j]);
}
}
return dist[0];
}
// Driver code
int main()
{
// Graph stored in the form of an
// adjacency Matrix
int graph[N][N] =
{{INF, 1, 2, 5, INF, INF, INF, INF},
{INF, INF, INF, INF, 4, 11, INF, INF},
{INF, INF, INF, INF, 9, 5, 16, INF},
{INF, INF, INF, INF, INF, INF, 2, INF},
{INF, INF, INF, INF, INF, INF, INF, 18},
{INF, INF, INF, INF, INF, INF, INF, 13},
{INF, INF, INF, INF, INF, INF, INF, 2}};
cout << shortestDist(graph);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/multistage-graph-shortest-path/
2148
Chapter 294
Newman-Conway Sequence
Input : n = 2
Output : 1
Input : n = 10
Output : 6
C++
2149
Chapter 294. Newman-Conway Sequence
Java
2150
Chapter 294. Newman-Conway Sequence
Python
C#
PHP
2151
Chapter 294. Newman-Conway Sequence
<?php
// PHP program for n-th element
// of Newman-Conway Sequence
// Recursive Function to
// find the n-th element
function sequence($n)
{
if ($n == 1 || $n == 2)
return 1;
else
return sequence(sequence($n - 1))+
sequence($n - sequence($n - 1));
}
// Driver Code
$n = 10;
echo(sequence($n));
// This code is contributed by Ajit.
?>
Output :
C++
2152
Chapter 294. Newman-Conway Sequence
Java
2153
Chapter 294. Newman-Conway Sequence
Python
C#
2154
Chapter 294. Newman-Conway Sequence
PHP
<?php
// PHP program to find the n-th element
// of Newman-Conway Sequence
// Function to find
// the n-th element
function sequence($n)
{
// Declare array to
// store sequence
$i;
$f[0] = 0;
$f[1] = 1;
$f[2] = 1;
for ($i = 3; $i <= $n; $i++)
$f[$i] = $f[$f[$i - 1]] +
$f[$i - $f[$i - 1]];
return $f[$n];
}
// Driver Code
$n = 10;
echo(sequence($n));
// This code is contributed by Ajit.
?>
2155
Chapter 294. Newman-Conway Sequence
Output :
Source
https://www.geeksforgeeks.org/newman-conway-sequence/
2156
Chapter 295
Newman–Shanks–Williams
prime
The first few terms of the sequence are 1, 1, 3, 7, 17, 41, 99, ….
Examples:
Input : n = 3
Output : 7
Input : n = 4
Output : 17
C++
2157
Chapter 295. Newman–Shanks–Williams prime
Java
2158
Chapter 295. Newman–Shanks–Williams prime
}
// This code is contributed by Anant Agarwal.
Python3
C#
// C# Program to find
// Newman-Shanks-Williams prime
using System;
class GFG {
// return nth Newman-Shanks-Williams
// prime
static int nswp(int n)
{
// Base case
if (n == 0 || n == 1)
return 1;
// Recursive step
return 2 * nswp(n - 1) + nswp(n - 2);
}
// Driver code
2159
Chapter 295. Newman–Shanks–Williams prime
PHP
<?php
// PHP Program to find
// Newman–Shanks–Williams prime
// return nth Newman –
// Shanks – Williams prime
function nswp($n)
{
// Base case
if ($n == 0 || $n == 1)
return 1;
// Recursive step
return 2 * nswp($n - 1) +
nswp($n - 2);
}
// Driver Code
$n = 3;
echo(nswp($n));
// This code is contributed by Ajit.
?>
Output:
C++
2160
Chapter 295. Newman–Shanks–Williams prime
Java
2161
Chapter 295. Newman–Shanks–Williams prime
return dp[n];
}
// Driver Program
public static void main (String[] args) {
int n = 3;
System.out.println(nswpn(n));
}
}
/* This code is contributed by Akash Singh */
Python3
C#
2162
Chapter 295. Newman–Shanks–Williams prime
// return nth Newman–Shanks–Williams prime
static int nswp(int n)
{
int[] dp = new int[n + 1];
// Base case
dp[0] = dp[1] = 1;
// Finding nth Newman–Shanks–Williams prime
for (int i = 2; i <= n; i++)
dp[i] = 2 * dp[i - 1] + dp[i - 2];
return dp[n];
}
// Driver Program
public static void Main()
{
int n = 3;
Console.WriteLine(nswp(n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to find
// Newman–Shanks–Williams prime
// return nth Newman–Shanks
// –Williams prime
function nswp($n)
{
// Base case
$dp[0] = $dp[1] = 1;
// Finding nth Newman–Shanks
// –Williams prime
for ($i = 2; $i <= $n; $i++)
$dp[$i] = 2 * $dp[$i - 1] +
$dp[$i - 2];
2163
Chapter 295. Newman–Shanks–Williams prime
return $dp[$n];
}
// Driver Code
$n = 3;
echo(nswp($n));
// This code is contributed by Ajit.
?>
Output:
Source
https://www.geeksforgeeks.org/newman-shanks-williams-prime/
2164
Chapter 296
Examples :
Input : n = 2
Output : 1
Input : n = 4
Output : 2
Input : n = 6
2165
Chapter 296. Non-crossing lines to connect points in a circle
Output : 5
Input : n = 3
Output : Invalid
n must be even.
We need to draw n/2 lines to connect n points. When we draw a line, we divide the points
in two sets that need to connected. Each set needs to be connected within itself. Below is
recurrence relation for the same.
Let m = n/2
2166
Chapter 296. Non-crossing lines to connect points in a circle
Java
2167
Chapter 296. Non-crossing lines to connect points in a circle
// A dynamic programming
// based function to find
// nth Catalan number
static int catalanDP(int n)
{
// Table to store
// results of subproblems
int []catalan = new int [n + 1];
// Initialize first
// two values in table
catalan[0] = catalan[1] = 1;
// Fill entries in catalan[]
// using recursive formula
for (int i = 2; i <= n; i++)
{
catalan[i] = 0;
for (int j = 0; j < i; j++)
catalan[i] += catalan[j] *
catalan[i - j - 1];
}
// Return last entry
return catalan[n];
}
// Returns count of ways to
// connect n points on a circle
// such that no two connecting
// lines cross each other and
// every point is connected
// with one other point.
static int countWays(int n)
{
// Throw error if n is odd
if (n < 1)
{
System.out.println("Invalid");
return 0;
}
// Else return n/2'th
// Catalan number
return catalanDP(n / 2);
}
2168
Chapter 296. Non-crossing lines to connect points in a circle
// Driver Code
public static void main (String[] args)
{
System.out.println(countWays(6) + " ");
}
}
// This code is contributed
// by akt_mit
C#
2169
Chapter 296. Non-crossing lines to connect points in a circle
return catalan[n];
}
// Returns count of ways to
// connect n points on a circle
// such that no two connecting
// lines cross each other and
// every point is connected
// with one other point.
static int countWays(int n)
{
// Throw error if n is odd
if (n < 1)
{
Console.WriteLine("Invalid");
return 0;
}
// Else return n/2'th
// Catalan number
return catalanDP(n / 2);
}
// Driver Code
static public void Main ()
{
Console.WriteLine(countWays(6) + " ");
}
}
// This code is contributed
// by M_kit
PHP
<?php
// PHP program to count number of
// ways to connect n (where n is
// even) points on a circle such
// that no two connecting lines
// cross each other and every
// point is connected with one
// other point.
// A dynamic programming based
// function to find nth Catalan number
function catalanDP($n)
{
2170
Chapter 296. Non-crossing lines to connect points in a circle
Output :
2171
Chapter 296. Non-crossing lines to connect points in a circle
Source
https://www.geeksforgeeks.org/non-crossing-lines-connect-points-circle/
2172
Chapter 297
Non-decreasing subsequence of
size k with minimum sum
Let solve(i, k) be the minimum sum of a subsequence of size k ending at index i. Then there
would be two states:
1. Include current element. {solve(j, k-1) + a[i]}
2. Exclude current element. {solve(j, k)}
Our recurrence state would be:
2173
Chapter 297. Non-decreasing subsequence of size k with minimum sum
C++
2174
Chapter 297. Non-decreasing subsequence of size k with minimum sum
// Driver code
int main()
{
initialize();
int a[] = { 58, 12, 11, 12, 82, 30,
20, 77, 16, 86 };
int n = sizeof(a) / sizeof(a[0]);
int k = 4;
cout << solve(a, n - 1, k) << endl;
return 0;
}
Java
2175
Chapter 297. Non-decreasing subsequence of size k with minimum sum
Python
2176
Chapter 297. Non-decreasing subsequence of size k with minimum sum
# when there is only one element
elif k == 1:
return min(a[: i + 1])
# Else two cases
# 1 include current element
# solve(a, j, k-1) + a[i]
# 2 ignore current element
# solve(a, j, k)
else:
ans = float('inf')
for j in xrange(i):
if a[i] >= a[j]:
ans = min(ans, solve(a, j, k), solve(a, j, k-1) + a[i])
else:
ans = min(ans, solve(a, j, k))
dp[i][k] = ans
return dp[i][k]
# Driver code
a = [58, 12, 11, 12, 82, 30, 20, 77, 16, 86]
print solve(a, len(a)-1, 4)
C#
2177
Chapter 297. Non-decreasing subsequence of size k with minimum sum
2178
Chapter 297. Non-decreasing subsequence of size k with minimum sum
120
Source
https://www.geeksforgeeks.org/non-decreasing-subsequence-of-size-k-with-minimum-sum/
2179
Chapter 298
Number of Co-prime pairs obtained from the sum of digits of elements in the given range -
GeeksforGeeks
Given two numbers A and B where 1 <= A <= B. The task is to count the number of
pairs whose elements are co-prime where pairs are formed from the sum of the digits of the
elements in the given range.
Note: Two pairs are counted as distinct if at least one of the number in the pair is
different. It may be assumed that the maximum digit sum can be 162.
Examples:
Input: 12 15
Output: 4
12 = 1+2 = 3
13 = 1+3 = 4
14 = 1+4 = 5
15 = 1+5 = 6
Thus pairs who are co-prime to each other are
(3, 4), (3, 5), (4, 5), (5, 6)
i.e the answer is 4.
Input: 7 10
Output: 5
Method-1:
2180
Chapter 298. Number of Co-prime pairs obtained from the sum of digits of elements in the
given range
C++
2181
Chapter 298. Number of Co-prime pairs obtained from the sum of digits of elements in the
given range
Java
2182
Chapter 298. Number of Co-prime pairs obtained from the sum of digits of elements in the
given range
while(k > 0)
{
sumOfDigits += k % 10;
k /= 10;
}
if (sumOfDigits <= 162)
pairs.add(sumOfDigits);
}
}
// Function to count
// the co-prime pairs
static int countCoPrime(int a, int b)
{
Vector<Integer> pairs = new Vector<Integer>();
// Function to make the pairs
// by doing the sum of digits
makePairs(pairs, a, b);
int count = 0;
// Count pairs that are co-primes
for(int i = 0; i < pairs.size(); i++)
for (int j = i+1; j < pairs.size(); j++)
if (GCD(pairs.get(i),
pairs.get(j)) == 1)
count++;
return count;
}
// Driver code
public static void main(String args[])
{
int a = 12, b = 15;
// Function to count the pairs
System.out.println(countCoPrime(a, b));
}
}
// This code is contributed by Arnab Kundu
Output:
2183
Chapter 298. Number of Co-prime pairs obtained from the sum of digits of elements in the
given range
Method-2:
As mentioned in the question, the maximum sum can be 162. So, find out the frequency of
numbers having their digit sum from 1 to 162 in range A to B and store the frequency in
the array. Later, find the answer using this frequency.
Since,
Number, Frequency
1, 0
2, 0
3, 1
4, 1
5, 1
6, 1
7, 0
8, 0
., .
., .
162, 0
Thus Number of gcd pairs = freq(3)*freq(4) + freq(3)*freq(5) + freq(4)*freq(5)
+ freq(5)* freq(6)
= 1+1+1+1
=4
Thus pairs who are co-prime to each other are (3,4), (3,5), (4,5), (5,6) i.e the answer is 4.
Below is the required implementation:
2184
Chapter 298. Number of Co-prime pairs obtained from the sum of digits of elements in the
given range
ll d;
// Loop from digit 0 to 9
for (d = 0; d < 10; ++d) {
newTight = false;
if (tight && st[idx] - '0' < d)
continue;
// To change the tight to 1
if (tight && st[idx] - '0' == d)
newTight = true;
// Calling the recursive function to find the frequency
if (sum >= d)
ans += recursive(idx + 1, sum - d,
newTight, st, dp, num);
}
return dp[idx][tight][sum] = ans;
}
// Function to find out frequency of numbers
// from 1 to N having their sum of digits
// from 1 to 162 and store them in array
vector<ll> formArray(ll N)
{
ll dp[20][2][166];
memset(dp, -1, sizeof dp);
// Number to string conversion
ostringstream x;
x << N;
string st = x.str();
ll num = st.size();
vector<ll> arr;
for (int i = 1; i <= 162; ++i) {
// Calling the recursive function
// and pushing it into array
arr.push_back(recursive(0, i, 1, st, dp, num));
}
return arr;
}
// Function to find the pairs
ll findPair(ll a, ll b)
2185
Chapter 298. Number of Co-prime pairs obtained from the sum of digits of elements in the
given range
{
// Calling the formArray function of a-1 numbers
vector<ll> arr_smaller = formArray(a - 1);
// Calling the formArray function of b numbers
vector<ll> arr_greater = formArray(b);
// Subtracting the frequency of higher number array with lower
// number array and thus finding the range of
// numbers from a to b having sum from 1 to 162
for (int i = 0; i < arr_greater.size(); ++i)
arr_greater[i] -= arr_smaller[i];
int ans = 0;
for (int i = 1; i <= 162; ++i) {
for (int j = i + 1; j <= 162; ++j) {
// To find out total number of pairs
// which are co-prime
if (__gcd(i, j) == 1)
ans = (ans + arr_greater[i - 1] * arr_greater[j - 1]);
}
}
return ans;
}
// Driver code
int main()
{
ll a = 12, b = 15;
// Function to count the pairs
cout << findPair(a, b);
return 0;
}
Output:
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/number-of-co-prime-pairs-obtained-from-the-sum-of-digits-of-elements-in-the-given
2186
Chapter 299
A naive approach is to iterate for every query from index to end, and find out the number
of next greater elements to the right. This won’t be efficient enough as we run two nested
loops .
Time complexity: O(n) to answer a query.
Auxiliary space: O(1)
Better approach is to store the next greater index of every element and run a loop for
every query that iterates from index and keeping the increasing counter as j = next[i]. This
will avoid checking all elements and will directly jump to the next greater element of every
element. But this won’t be efficient enough in cases like 1 2 3 4 5 6, where the next greater
elements are sequentially increasing, ending it up in taking O(n) for every query.
Time complexity : O(n) to answer a query.
Auxiliary space : O(n) for next greater element.
2187
Chapter 299. Number of NGEs to the right
Efficient approach is to store the next greater elements index using next greater element
in a next[] array. Then create a dp[] array that starts from n-2, as n-1th index will have
no elements to its right and dp[n-1] = 0. While traversing from back we use dynamic
programming to count the number of elements to the right where we use memoization as
dp[next[i]] which gives us a count of the numbers to the right of the next greater element of
the current element, hence we add 1 to it. If next[i]=-1 then we do not have any element to
the right hence dp[i]=0. dp[index] stores the count of the number of next greater elements
to the right.
Below is the c++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// array to store the next greater element index
void fillNext(int next[], int a[], int n)
{
// use of stl stack in c++
stack<int> s;
// push the 0th index to the stack
s.push(0);
// traverse in the loop from 1-nth index
for (int i = 1; i < n; i++) {
// iterate till loop is empty
while (!s.empty()) {
// get the topmost index in the stack
int cur = s.top();
// if the current element is greater
// then the top index-th element, then
// this will be the next greatest index
// of the top index-th element
if (a[cur] < a[i]) {
// initialize the cur index position's
// next greatest as index
next[cur] = i;
// pop the cur index as its greater
// element has been found
s.pop();
}
// if not greater then break
else
2188
Chapter 299. Number of NGEs to the right
break;
}
// push the i index so that its next greatest
// can be found
s.push(i);
}
// iterate for all other index left inside stack
while (!s.empty()) {
int cur = s.top();
// mark it as -1 as no element in greater
// then it in right
next[cur] = -1;
s.pop();
}
}
// function to count the number of next greater numbers to the right
void count(int a[], int dp[], int n)
{
// initializes the next array as 0
int next[n];
memset(next, 0, sizeof(next));
// calls the function to pre-calculate
// the next greatest element indexes
fillNext(next, a, n);
for (int i = n - 2; i >= 0; i--) {
// if the i-th element has no next
// greater element to right
if (next[i] == -1)
dp[i] = 0;
// Count of next greater numbers to right.
else
dp[i] = 1 + dp[next[i]];
}
}
// answers all queries in O(1)
int answerQuery(int dp[], int index)
{
2189
Chapter 299. Number of NGEs to the right
Output:
2
0
3
Source
https://www.geeksforgeeks.org/number-nges-right/
2190
Chapter 300
Examples:
Input: n = 3
Output: 5
For n = 3, preorder traversal of Unique BSTs are:
1. 1 2 3
2. 1 3 2
3. 2 1 3
4. 3 1 2
5. 3 2 1
Input: 4
Output: 14
In the previous post a O(n) solution has been discussed. In this post we will discuss a
solution based on Dynamic Programming. For all possible values of i, consider i as root,
then [1….i-1] numbers will fall in the left subtree and [i+1….n] numbers will fall in the right
subtree. So, add (i-1)*(n-i) to the answer. The summation of the products will be the
answer to the number of unique BST.
Below is the implementation for above approach:
2191
Chapter 300. Number of Unique BST with a given key | Dynamic Programming
C++
Java
2192
Chapter 300. Number of Unique BST with a given key | Dynamic Programming
import java.util.Arrays;
class GFG
{
static int numberOfBST(int n)
{
// DP to store the number
// of unique BST with key i
int dp[] = new int[n + 1];
Arrays.fill(dp, 0);
// Base case
dp[0] = 1;
dp[1] = 1;
// fill the dp table in
// top-down approach.
for (int i = 2; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
// n-i in right * i-1 in left
dp[i] = dp[i] + (dp[i - j] *
dp[j - 1]);
}
}
return dp[n];
}
// Driver Code
public static void main (String[] args)
{
int n = 3;
System.out.println("Number of structurally " +
"Unique BST with "+ n +
" keys are : " +
numberOfBST(n));
}
}
// This code is contributed
// by shiv_bhakt.
C#
2193
Chapter 300. Number of Unique BST with a given key | Dynamic Programming
PHP
2194
Chapter 300. Number of Unique BST with a given key | Dynamic Programming
<?php
// PHP code to find number
// of unique BSTs Dynamic
// Programming solution
// Function to find number
// of unique BST
function numberOfBST($n)
{
// DP to store the number
// of unique BST with key i
$dp = array($n + 1);
for($i = 0; $i <= $n + 1; $i++)
$dp[$i] = 0;
// Base case
$dp[0] = 1;
$dp[1] = 1;
// fill the dp table
// in top-down approach.
for ($i = 2; $i <= $n; $i++)
{
for ($j = 1; $j <= $i; $j++)
{
// n-i in right *
// i-1 in left
$dp[$i] += (($dp[$i - $j]) *
($dp[$j - 1]));
}
}
return $dp[$n];
}
// Driver Code
$n = 3;
echo "Number of structurally ".
"Unique BST with " ,
$n , " keys are : " ,
numberOfBST($n) ;
// This code is contributed
// by shiv_bhakt.
?>
2195
Chapter 300. Number of Unique BST with a given key | Dynamic Programming
Output:
Source
https://www.geeksforgeeks.org/number-of-unique-bst-with-a-given-key-dynamic-programming/
2196
Chapter 301
Number of arrays of size N whose elements are positive integers and sum is K - GeeksforGeeks
Given two positive integers N and K. The task is to find the number of arrays of size N
that can be formed such that elements of the array should be positive integers and the sum
of elements is equal to K.
Examples:
Input : N = 2, K = 3
Output : 2
Explanation: [1, 2] and [2, 1] are the only arrays of size 2 whose sum is 3.
Input : n = 3, k = 7
Output : 15
2197
Chapter 301. Number of arrays of size N whose elements are positive integers and sum is
K
C++
Java
2198
Chapter 301. Number of arrays of size N whose elements are positive integers and sum is
K
C#
2199
Chapter 301. Number of arrays of size N whose elements are positive integers and sum is
K
2200
Chapter 301. Number of arrays of size N whose elements are positive integers and sum is
K
}
// This code is contributed by ajit
PHP
<?php
// PHP Program to find the
// number of arrays of size
// N whose elements are
// positive integers and
// sum is K
// Return nCr
function binomialCoeff($n, $k)
{
$C = array_fill(0, ($k + 1), 0);
$C[0] = 1; // nC0 is 1
for ($i = 1; $i <= $n; $i++)
{
// Compute next row
// of pascal triangle
// using the previous row
for ($j = min($i, $k);
$j > 0; $j--)
$C[$j] = $C[$j] +
$C[$j - 1];
}
return $C[$k];
}
// Return the number of
// array that can be
// formed of size n and
// sum equals to k.
function countArray($N, $K)
{
return binomialCoeff($K - 1,
$N - 1);
}
// Driver Code
$N = 2;
$K = 3;
echo countArray($N, $K);
2201
Chapter 301. Number of arrays of size N whose elements are positive integers and sum is
K
// This code is contributed by mits
?>
Output:
Source
https://www.geeksforgeeks.org/number-arrays-size-n-whose-elements-positive-integers-sum-k/
2202
Chapter 302
Input : n = 3, c = 3
a[] = { 3, 1, 2 }
b[] = { 2, 2, 2 }
Output : 2
Explanation:
If we starts with 0th petrol pump, we will gain
3 (a[0]) litres of petrol and lose 2 litre (b[0] to travel
to 1st petrol pump.On refueling 1 litre (a[1])
of petrol on 1st petrol pump, we will lose 2
litres (b[0]) of petrol to reach 2nd petrol pump.
Now the tank is empty.On refueling 2 litres (a[2]) of petrol
at 2nd petrol pump, we can travel back 0th
petrol pump.
If we starts from 1st petrol pump, we will gain 1
litre of petrol but to travel to 2nd petrol pump
we need 2 litres of petrol, which we don’t have. So, we cannot
starts from 1st petrol pump.
If we starts from 2nd petrol pump, we will gain 2
litres of petrol and travel to 0th petrol pump by
2203
Chapter 302. Number of circular tours that visit all petrol pumps
Approach:
The problem involves 2 parts, first involves if a valid starting petrol pump exists and second,
if such a petrol pump exists, check if the petrol pump before it can also be used as a starting
petrol pump.
First, lets start from a petrol pump s and travel to petrol pump, s + 1, s + 2, s + 3 till
s + j, suppose we run out of fuel before we go to petrol pump s + j + 1, then no petrol
pump between s and s + j can be used as starting petrol pump. Hence, we start over with
s + j + 1 as the starting petrol pump. If no such petrol pump exists after all petrol pumps
are exhausted, the answer is 0. This step takes O(n).
Second, lets visit one such valid petrol pump (lets call it s). The petrol pump before s i.e s
– 1 can also be a start petrol pump provided the vehicle can start at s – 1 and reach s.
If a[i] is take fuel available at petrol pump i, and c be the capacity of the fuel tank, and
b[i] is the amount of fuel the vehicle takes to travel from petrol pump i to i + 1, then lets
define need[i] as follows:
need[i] is the extra fuel, if present in the vehicle at the beginning of the journey at petrol
pump i (excluding a[i]_, it can be a valid petrol pump.
If need[i] = 0, then petrol pump i is a valid starting petrol pump. We know that need[s] =
0 from step 1. We can evaluate if s – 1, s – 2, … are starting petrol pumps are not. This
step also takes O(n).
2204
Chapter 302. Number of circular tours that visit all petrol pumps
2205
Chapter 302. Number of circular tours that visit all petrol pumps
{
int n = 3;
int c = 3;
int a[2 * N] = { 3, 1, 2 };
int b[2 * N] = { 2, 2, 2 };
cout << count(n, c, a, b) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/number-of-circular-tours-that-visit-all-petrol-pumps/
2206
Chapter 303
Input : 2
Output : 36
Numbers are 12, 13, ... 19, 23
24, ... 29, .... 89.
Input : 3
Output : 84
2207
Chapter 303. Number of decimal numbers of length k, that are strict monotone
#include <cstring>
#include <iostream>
int static const DP_s = 9;
int getNumStrictMonotone(int len)
{
// DP[i][j] is going to store monotone
// numbers of length i+1 considering
// j+1 digits (1, 2, 3, ..9)
int DP[len][DP_s];
memset(DP, 0, sizeof(DP));
// Unit length numbers
for (int i = 0; i < DP_s; ++i)
DP[0][i] = i + 1;
// Building dp[] in bottom up
for (int i = 1; i < len; ++i)
for (int j = 1; j < DP_s; ++j)
DP[i][j] = DP[i - 1][j - 1] + DP[i][j - 1];
return DP[len - 1][DP_s - 1];
}
// Driver code
int main()
{
std::cout << getNumStrictMonotone(2);
return 0;
}
Java
2208
Chapter 303. Number of decimal numbers of length k, that are strict monotone
Python3
2209
Chapter 303. Number of decimal numbers of length k, that are strict monotone
C#
2210
Chapter 303. Number of decimal numbers of length k, that are strict monotone
PHP
<?php
// PHP program to count
// numbers of k digits
// that are strictly
// monotone.
$DP_s = 9;
function getNumStrictMonotone($len)
{
global $DP_s;
// DP[i][j] is going to
// store monotone numbers
// of length i+1 considering
// j+1 digits (1, 2, 3, ..9)
$DP = array(array());
for($i = 0; $i < $len; $i++)
{
for($j = 0; $j < $DP_s; $j++)
$DP[$i][$j] = 0;
}
// Unit length numbers
for ($i = 0; $i < $DP_s; ++$i)
$DP[0][$i] = $i + 1;
// Building dp[]
// in bottom up
for ($i = 1; $i < $len; ++$i)
for ($j = 1; $j < $DP_s; ++$j)
$DP[$i][$j] = $DP[$i - 1][$j - 1] +
$DP[$i][$j - 1];
return $DP[$len - 1][$DP_s - 1];
}
// Driver code
echo (getNumStrictMonotone(2));
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output :
2211
Chapter 303. Number of decimal numbers of length k, that are strict monotone
36
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/number-decimal-numbers-length-k-strict-monotone/
2212
Chapter 304
Input: 2
Output: 3
The paths of length 2 which starts and ends at D are:
B-A-B
B-D-B
B-C-B
Input: 3
Output: 6
Approach: Dynamic Programming can be used to keep track of the number of paths for
previous values of N. Check for the number of moves which are left and where are we when
we are moving in a path. That is 4n states, each with 3 options. Observe that all the vertices
A, B, C are equivalent. Let zB be 1 initially and as at 0 steps, we can reach B itself only.
Let zACD be 1 as paths for reaching other vertexes A, C and D is 0. Hence the recurrence
relation formed will be:
2213
Chapter 304. Number of different cyclic paths of length N in a tetrahedron
At every step, zADC gets multiplied by 2 (2 states) and it is added by zB since zB is the
number of paths at step n-1 which comprises of the remaining 2 states.
Below is the implementation of the above approach:
C++
2214
Chapter 304. Number of different cyclic paths of length N in a tetrahedron
Java
2215
Chapter 304. Number of different cyclic paths of length N in a tetrahedron
Output:
Improved By : jit_t
Source
https://www.geeksforgeeks.org/number-of-different-cyclic-paths-of-length-n-in-a-tetrahedron/
2216
Chapter 305
Input : 2
Output : 17
Explanation: The numbers are 10, 12, 21,
23, 32, 34, 43, 45, 54, 56, 65, 67, 76,
78, 87, 89, 98.
Input : 1
Output : 10
Explanation: the numbers are 0, 1, 2, 3,
4, 5, 6, 7, 8, 9.
A naive approach is to run a loop for all n digit numbers and check for every number if
it is Stepping.
An efficient approach is to use dynamic programming.
2217
Chapter 305. Number of n digit stepping numbers
dp(i, j) = 1;
// If last digit is 0.
if (j == 0)
dp(i, j) = dp(i-1, j+1)
// If last digit is 9
else if (j == 9)
dp(i, j) = dp(i-1, j-1)
C++
2218
Chapter 305. Number of n digit stepping numbers
Java
2219
Chapter 305. Number of n digit stepping numbers
// Initialize values for count of
// digits equal to 1.
for (int j = 0; j <= 9; j++)
dp[1][j] = 1;
// Compute values for count of
// digits more than 1.
for (int i = 2; i <= n; i++) {
for (int j = 0; j <= 9; j++) {
// If ending digit is 0
if (j == 0)
dp[i][j] = dp[i - 1][j + 1];
// If ending digit is 9
else if (j == 9)
dp[i][j] = dp[i - 1][j - 1];
// For other digits.
else
dp[i][j] = dp[i - 1][j - 1] +
dp[i - 1][j + 1];
}
}
// stores the final answer
long sum = 0;
for (int j = 1; j <= 9; j++)
sum += dp[n][j];
return sum;
}
// driver program to test the above function
public static void main(String args[])
{
int n = 2;
System.out.println(answer(n));
}
}
/*This code is contributed by Nikita tiwari.*/
Python3
2220
Chapter 305. Number of n digit stepping numbers
# function that calculates
# the answer
def answer(n):
# dp[i][j] stores count of
# i digit stepping numbers
# ending with digit j.
dp = [[0 for x in range(10)]
for y in range(n + 1)];
# if n is 1 then answer
# will be 10.
if (n == 1):
return 10;
for j in range(10):
dp[1][j] = 1;
# Compute values for count
# of digits more than 1.
for i in range(2, n + 1):
for j in range(10):
# If ending digit is 0
if (j == 0):
dp[i][j] = dp[i - 1][j + 1];
# If ending digit is 9
elif (j == 9):
dp[i][j] = dp[i - 1][j - 1];
# For other digits.
else:
dp[i][j] = (dp[i - 1][j - 1] +
dp[i - 1][j + 1]);
# stores the final answer
sum = 0;
for j in range(1, 10):
sum = sum + dp[n][j];
return sum;
# Driver Code
n = 2;
print(answer(n));
# This code is contributed
# by mits
2221
Chapter 305. Number of n digit stepping numbers
C#
2222
Chapter 305. Number of n digit stepping numbers
PHP
<?php
// PHP program to calculate
// the number of n digit
// stepping numbers.
// function that calculates
// the answer
function answer($n)
{
// dp[i][j] stores count of
// i digit stepping numbers
// ending with digit j.
// if n is 1 then answer
// will be 10.
if ($n == 1)
return 10;
for ( $j = 0; $j <= 9; $j++)
$dp[1][$j] = 1;
// Compute values for count
// of digits more than 1.
for ($i = 2; $i <= $n; $i++)
{
for ($j = 0; $j <= 9; $j++)
{
// If ending digit is 0
if ($j == 0)
2223
Chapter 305. Number of n digit stepping numbers
Output :
17
Source
https://www.geeksforgeeks.org/number-n-digit-stepping-numbers/
2224
Chapter 306
Number of n-digits
non-decreasing integers
Input : n = 1
Output : 10
Numbers are 0, 1, 2, ...9.
Input : n = 2
Output : 55
Input : n = 4
Output : 715
Naive Approach : We generate all possible n-digit numbers and then for each number we
check whether it is non-decreasing or not.
Time Complexity : (n*10^n), where 10^n is for generating all possible n-digits number and
n is for checking whether a particular number is non-decreasing or not.
Dynamic Programming :
If we fill digits one by one from left to right, following conditions hold.
2225
Chapter 306. Number of n-digits non-decreasing integers
1. If current last digit is 9, we can fill only 9s in remaining places. So only one solution
is possible if current last digit is 9.
2. If current last digit is less than 9, then we can recursively compute count using following
formula.
We build a matrix a[][] where a[i][j] = count of all valid i-digit non-decreasing integers with
j or greater than j as the leading digit. The solution is based on below observations. We
fill this matrix column-wise, first calculating a[1][9] then using this value to compute a[2][8]
and so on.
At any instant if we wish to calculate a[i][j] means number of i-digits non-decreasing
integers with leading digit as j or digit greater than j, we should add up a[i-1][j] (number of
i-1 digit integers which should start from j or greater digit, because in this case if we place
j as its left most digit then our number will be i-digit non-decreasing number) and a[i][j+1]
(number of i-digit integers which should start with digit equals to greater than j+1). So,
a[i][j] = a[i-1][j] + a[i][j+1].
2226
Chapter 306. Number of n-digits non-decreasing integers
C/C++
2227
Chapter 306. Number of n-digits non-decreasing integers
/* Initialization of all i-digit
non-decreasing number leading with 9*/
for (int i = 1; i <= n; i++)
a[i][9] = 1;
/* for all digits we should calculate
number of ways depending upon leading
digits*/
for (int i = 1; i <= n; i++)
for (int j = 8; j >= 0; j--)
a[i][j] = a[i - 1][j] + a[i][j + 1];
return a[n][0];
}
// driver program
int main()
{
int n = 2;
cout << "Non-decreasing digits = "
<< nonDecNums(n) << endl;
return 0;
}
Java
2228
Chapter 306. Number of n-digits non-decreasing integers
a[i][9] = 1;
// for all digits we should calculate
// number of ways depending upon leading
// digits
for (int i = 1; i <= n; i++)
for (int j = 8; j >= 0; j--)
a[i][j] = a[i - 1][j] + a[i][j + 1];
return a[n][0];
}
// driver program
public static void main(String[] args)
{
int n = 2;
System.out.println("Non-decreasing digits = " + nonDecNums(n));
}
}
// Contributed by Pramod Kumar
C#
2229
Chapter 306. Number of n-digits non-decreasing integers
PHP
<?php
// PHP program for counting
// n digit numbers with
// non decreasing digits
// Returns count of non-
// decreasing numbers with
// n digits.
function nonDecNums($n)
{
/* a[i][j] = count of
all possible number
with i digits having
leading digit as j */
// Initialization of
// all 0-digit number
for ($i = 0; $i <= 9; $i++)
$a[0][$i] = 1;
/* Initialization of all
i-digit non-decreasing
number leading with 9*/
for ($i = 1; $i <= $n; $i++)
$a[$i][9] = 1;
2230
Chapter 306. Number of n-digits non-decreasing integers
/* for all digits we should
calculate number of ways
depending upon leading digits*/
for ($i = 1; $i <= $n; $i++)
for ($j = 8; $j >= 0; $j--)
$a[$i][$j] = $a[$i - 1][$j] +
$a[$i][$j + 1];
return $a[$n][0];
}
// Driver Code
$n = 2;
echo "Non-decreasing digits = ",
nonDecNums($n),"\n";
// This code is contributed by m_kit
?>
Output :
Non-decreasing digits = 55
Source
https://www.geeksforgeeks.org/number-n-digits-non-decreasing-integers/
2231
Chapter 307
Input : n = 1
Output : 3
There are four ways to get sum 1.
(1, 0, 0), (0, 1, 0) and (0, 0, 1)
Input : n = 2
Output : 6
There are six ways to get sum 2.
(2, 0, 0), (0, 2, 0), (0, 0, 2), (1, 1, 0)
(1, 0, 1) and (0, 1, 1)
Input : n = 3
Output : 10
There are ten ways to get sum 10.
(3, 0, 0), (0, 3, 0), (0, 0, 3), (1, 2, 0)
(1, 0, 2), (0, 1, 2), (2, 1, 0), (2, 0, 1),
(0, 2, 1) and (1, 1, 1)
2232
Chapter 307. Number of non-negative integral solutions of a + b + c = n
C++
Java
2233
Chapter 307. Number of non-negative integral solutions of a + b + c = n
// Consider all triplets and increment
// result whenever sum of a triplet is n.
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n - i; j++)
for (int k = 0; k <= (n - i - j); k++)
if (i + j + k == n)
result++;
return result;
}
// Driver code
public static void main (String[] args)
{
int n = 3;
System.out.println( countIntegralSolutions(n));
}
}
// This article is contributed by vt_m
Python3
2234
Chapter 307. Number of non-negative integral solutions of a + b + c = n
print(countIntegralSolutions(n))
# This code is contributed by "Sharad_Bhardwaj".
C#
PHP
<?php
// A naive PHP solution
// to count solutions of
2235
Chapter 307. Number of non-negative integral solutions of a + b + c = n
// a + b + c = n
// Returns count of
// solutions of a + b + c = n
function countIntegralSolutions( $n)
{
// Initialize result
$result = 0;
// Consider all triplets and increment
// result whenever sum of a triplet is n.
for ($i = 0; $i <= $n; $i++)
for ($j = 0; $j <= $n - $i; $j++)
for ($k = 0; $k <= ($n - $i - $j); $k++)
if ($i + $j + $k == $n)
$result++;
return $result;
}
// Driver Code
$n = 3;
echo countIntegralSolutions($n);
// This code is contributed by anuj_67.
?>
Output :
10
C++
2236
Chapter 307. Number of non-negative integral solutions of a + b + c = n
Java
Python3
2237
Chapter 307. Number of non-negative integral solutions of a + b + c = n
C#
// C# solution to count
// solutions of a + b + c = n
using System;
class GFG {
// Returns count of solutions
// of a + b + c = n
static int countIntegralSolutions(int n)
{
return ((n + 1) * (n + 2)) / 2;
}
// Driver code
public static void Main (String[] args)
{
int n = 3;
Console.Write ( countIntegralSolutions(n));
}
}
// This code is contributed by parashar.
PHP
<?php
// A naive PHP solution
// to count solutions of
// a + b + c = n
// Returns count of solutions
// of a + b + c = n
function countIntegralSolutions($n)
{
return (($n + 1) * ($n + 2)) / 2;
2238
Chapter 307. Number of non-negative integral solutions of a + b + c = n
}
// Driver Code
$n = 3;
echo countIntegralSolutions($n);
// This code is contributed by anuj_67.
?>
Output :
10
Source
https://www.geeksforgeeks.org/number-non-negative-integral-solutions-b-c-n/
2239
Chapter 308
Input : A[]={5, 4, 1, 6}
Output : 4
Explanation : (4, 1), (1, 4), (6, 1) and (1, 6) are the pairs
Simple approach : A simple approach is to check for all possible pairs and count the
number of ordered pairs whose bitwise & returns 0.
Below is the implementation of above idea:
C++
2240
Chapter 308. Number of ordered pairs such that (Ai & Aj) = 0
// and is zero
#include <bits/stdc++.h>
using namespace std;
// Naive function to count the number
// of ordered pairs such that their
// bitwise and is 0
int countPairs(int a[], int n)
{
int count = 0;
// check for all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++)
if ((a[i] & a[j]) == 0)
// add 2 as (i, j) and (j, i) are
// considered different
count += 2;
}
return count;
}
// Driver Code
int main()
{
int a[] = { 3, 4, 2 };
int n = sizeof(a) / sizeof(a[0]);
cout << countPairs(a, n);
return 0;
}
Java
2241
Chapter 308. Number of ordered pairs such that (Ai & Aj) = 0
Python3
2242
Chapter 308. Number of ordered pairs such that (Ai & Aj) = 0
n = len(a)
print (countPairs(a, n))
# This code is contributed
# by Shreyanshi Arun.
C#
PHP
2243
Chapter 308. Number of ordered pairs such that (Ai & Aj) = 0
<?php
// PHP program to calculate the number
// of ordered pairs such that their
// bitwise and is zero
// Naive function to count the number
// of ordered pairs such that their
// bitwise and is 0
function countPairs($a, $n)
{
$count = 0;
// check for all possible pairs
for ($i = 0; $i < $n; $i++)
{
for ($j = $i + 1; $j < $n; $j++)
if (($a[$i] & $a[$j]) == 0)
// add 2 as (i, j) and (j, i) are
// considered different
$count += 2;
}
return $count;
}
// Driver Code
{
$a = array(3, 4, 2);
$n = sizeof($a) / sizeof($a[0]);
echo countPairs($a, $n);
return 0;
}
// This code is contributed by nitin mittal
?>
Output:
2244
Chapter 308. Number of ordered pairs such that (Ai & Aj) = 0
occurrence of every element. If the last bit is OFF, then relating to SOS dp, we will have a
base case since there is only one possibility of OFF bit.
dp[mask][0] = freq(mask)
If the last bit is set ON, then we will have the base case as:
Now the second case, if the i-th bit is 1, it can be divided into two non-intersecting
sets. One containing numbers with i-th bit as 1 and differing from mask in the next (i-1)
bits. Second containing numbers with ith bit as 0 and differing from mask (2i ) in next
(i-1) bits. Hence,
DP[mask][i] stores the number of subsets of mask which differ from mask only in first i
bits. Iterate for all array elements, and for every array element add the number of subsets
(dp[ ( ( 1<<N ) – 1 ) ^ a[i] ][ N ]) to the number of pairs. N = maximum number of bits.
Explanation of addition of dp[ ( ( 1<<N ) – 1 ) ^ a[i] ][N] to the number of pairs:
Take an example of A[i] being 5, which is 101 in binary. For better understanding, assume
N=3 in this case, therefore, the reverse of 101 will be 010 which on applying bitwise & gives
0. So (1<<3) gives 1000 which on subtraction from 1 gives 111. 111 101 gives 010 which
is the reversed bit.So dp[((1<<N)-1)^a[i]][N] will have the number of subsets that returns
0 on applying bitwise & operator.
Below is the implementation of the above idea:
2245
Chapter 308. Number of ordered pairs such that (Ai & Aj) = 0
2246
Chapter 308. Number of ordered pairs such that (Ai & Aj) = 0
Output:
Time Complexity: O(N*2N ) where N=15 which is maximum number of bits possible,
since Amax =104 .
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/number-ordered-pairs-ai-aj-0/
2247
Chapter 309
We can solve this problem recursively, we start from two corners of a palindromic path(top-
left and bottom right). In each recursive call, we maintain a state which will constitute two
cells one from starting and one from end which should be equal for palindrome property. If
at a state, both cell characters are equal then we call recursively with all possible movements
in both directions.
2248
Chapter 309. Number of palindromic paths in a matrix
As this can lead to solving same subproblem multiple times, we have taken a map memo in
below code which stores the calculated result with key as indices of starting and ending cell
so if subproblem with same starting and ending cell is called again, result will be returned
by memo directly instead of recalculating again.
Please see below code for better understanding,
2249
Chapter 309. Number of palindromic paths in a matrix
// return 0
if (rs < 0 || rs >= R || cs < 0 || cs >= C)
return 0;
if (re < 0 || re < rs || ce < 0 || ce < cs)
return 0;
// Base case 2 : if values are not equal
// then palindrome property rs not satisfied,
// so return 0
if (mat[rs][cs] != mat[re][ce])
return 0;
// If we reach here, then matrix cells are same.
// Base Case 3 : if indices are adjacent then
// return 1
if (abs((rs - re) + (cs - ce)) <= 1)
return 1;
// if result rs precalculated, return from map
if (memo.find(cells(rs, cs, re, ce)) != memo.end())
return memo[cells(rs, cs, re, ce)];
int ret = 0; // Initialize result
// calling recursively for all possible movements
ret += getPalindromicPathsRecur(mat, rs + 1, cs,
re - 1, ce, memo);
ret += getPalindromicPathsRecur(mat, rs + 1, cs, re,
ce - 1, memo);
ret += getPalindromicPathsRecur(mat, rs, cs + 1,
re - 1, ce, memo);
ret += getPalindromicPathsRecur(mat, rs, cs + 1, re,
ce - 1, memo);
// storing the calculated result in map
memo[cells(rs, cs, re, ce)] = ret;
return ret;
}
// method returns number of palindromic paths in matrix
int getPalindromicPaths(char mat[R][C])
{
map<cells, int> memo;
return getPalindromicPathsRecur(mat, 0, 0, R - 1,
C - 1, memo);
}
2250
Chapter 309. Number of palindromic paths in a matrix
// Driver code to test above methods
int main()
{
char mat[R][C] =
{
'a', 'a', 'a', 'b',
'b', 'a', 'a', 'a',
'a', 'b', 'b', 'a'
};
printf("%d", getPalindromicPaths(mat));
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/number-of-palindromic-paths-in-a-matrix/
2251
Chapter 310
Number of palindromic
subsequences of length k where
k <= 3
Input : s = “aabab”, k = 2
Output : 4
Input : s = “aaa”, k = 3
Output : 1
For k = 1, we can easily say that number of characters in string will be the answer.
For k = 2, we can easily make pairs of same characters so we have to maintain the count
of each character in string and then calculate
sum = 0
for character 'a' to 'z'
cnt = count(characater)
sum = sum + cnt*(cnt-1)/2
sum is the answer.
Now as k increases, it became difficult to find. How to find answer for k = 3 ? So the idea
is to see that palindromes of length 3 will be of the format TZT, so we have to maintain
two matrices, one to calculate the prefix sum of each character, and one to calculate suffix
2252
Chapter 310. Number of palindromic subsequences of length k where k <= 3
L[X][i-1] * R[X][i+1],
where i is the range [1, n-2] and
X will be from 'a' to 'z'
C++
2253
Chapter 310. Number of palindromic subsequences of length k where k <= 3
r[s[i] - 'a'][i]++;
}
}
// Find the number of palindromic subsequence of
// length k
int countPalindromes(int k, int n, int l[][MAX],
int r[][MAX])
{
int ans = 0;
// If k is 1.
if (k == 1) {
for (int i = 0; i < MAX_CHAR; i++)
ans += l[i][n - 1];
return ans;
}
// If k is 2
if (k == 2) {
// Adding all the products of prefix array
for (int i = 0; i < MAX_CHAR; i++)
ans += ((l[i][n - 1] * (l[i][n - 1] - 1)) / 2);
return ans;
}
// For k greater than 2. Adding all the products
// of value of prefix and suffix array.
for (int i = 1; i < n - 1; i++)
for (int j = 0; j < MAX_CHAR; j++)
ans += l[j][i - 1] * r[j][i + 1];
return ans;
}
// Driven Program
int main()
{
string s = "aabab";
int k = 2;
int n = s.length();
int l[MAX_CHAR][MAX] = { 0 }, r[MAX_CHAR][MAX] = { 0 };
precompute(s, n, l, r);
cout << countPalindromes(k, n, l, r) << endl;
return 0;
}
2254
Chapter 310. Number of palindromic subsequences of length k where k <= 3
Java
2255
Chapter 310. Number of palindromic subsequences of length k where k <= 3
}
// If k is 2
if (k == 2) {
// Adding all the products of prefix array
for (int i = 0; i < MAX_CHAR; i++)
ans += ((l[i][n - 1] * (l[i][n - 1] - 1)) / 2);
return ans;
}
// For k greater than 2. Adding all the products
// of value of prefix and suffix array.
for (int i = 1; i < n - 1; i++)
for (int j = 0; j < MAX_CHAR; j++)
ans += l[j][i - 1] * r[j][i + 1];
return ans;
}
// Driver code
public static void main (String[] args)
{
String s = "aabab";
int k = 2;
int n = s.length();
int l[][]=new int[MAX_CHAR][MAX];
int r[][]=new int[MAX_CHAR][MAX];
precompute(s, n, l, r);
System.out.println(countPalindromes(k, n, l, r));
}
}
// This code is contributed by Anant Agarwal.
Python3
2256
Chapter 310. Number of palindromic subsequences of length k where k <= 3
l[ord(s[0]) - ord('a')][0] = 1
# Precompute the prefix 2D array
for i in range(1, n):
for j in range(MAX_CHAR):
l[j][i] += l[j][i - 1]
l[ord(s[i]) - ord('a')][i] += 1
r[ord(s[n - 1]) - ord('a')][n - 1] = 1
# Precompute the Suffix 2D array.
k = n - 2
while(k >= 0):
for j in range(MAX_CHAR):
r[j][k] += r[j][k + 1]
r[ord(s[k]) - ord('a')][k] += 1
k -= 1
# Find the number of palindromic
# subsequence of length k
def countPalindromes(k, n, l, r):
ans = 0
# If k is 1.
if (k == 1):
for i in range(MAX_CHAR):
ans += l[i][n - 1]
return ans
# If k is 2
if (k == 2):
# Adding all the products of
# prefix array
for i in range(MAX_CHAR):
ans += ((l[i][n - 1] * (l[i][n - 1] - 1)) / 2)
return ans
# For k greater than 2. Adding all
# the products of value of prefix
# and suffix array.
for i in range(1, n - 1):
for j in range(MAX_CHAR):
ans += l[j][i - 1] * r[j][i + 1]
return ans
# Driven Program
2257
Chapter 310. Number of palindromic subsequences of length k where k <= 3
s = "aabab"
k = 2
n = len(s)
l = [[0 for x in range(MAX)] for y in range(MAX_CHAR)]
r = [[0 for x in range(MAX)] for y in range(MAX_CHAR)]
precompute(s, n, l, r)
print (countPalindromes(k, n, l, r))
# This code is written by Sachin Bisht
C#
2258
Chapter 310. Number of palindromic subsequences of length k where k <= 3
r[s[i] - 'a',i]++;
}
}
// Find the number of palindromic
// subsequence of length k
static int countPalindromes(int k, int n,
int [,]l, int [,]r)
{
int ans = 0;
// If k is 1.
if (k == 1)
{
for (int i = 0; i < MAX_CHAR; i++)
ans += l[i,n - 1];
return ans;
}
// If k is 2
if (k == 2) {
// Adding all the products
// of prefix array
for (int i = 0; i < MAX_CHAR; i++)
ans += ((l[i,n - 1] *
(l[i,n - 1] - 1)) / 2);
return ans;
}
// For k greater than 2.
// Adding all the products
// of value of prefix and
// suffix array.
for (int i = 1; i < n - 1; i++)
for (int j = 0; j < MAX_CHAR; j++)
ans += l[j,i - 1] * r[j, i + 1];
return ans;
}
// Driver code
public static void Main ()
{
string s = "aabab";
int k = 2;
2259
Chapter 310. Number of palindromic subsequences of length k where k <= 3
int n = s.Length;
int [,]l=new int[MAX_CHAR,MAX];
int [,]r=new int[MAX_CHAR,MAX];
precompute(s, n, l, r);
Console.Write(countPalindromes(k, n, l, r));
}
}
// This code is contributed by Nitin Mittal.
Output:
Source
https://www.geeksforgeeks.org/number-of-palindromic-subsequences-of-length-k-where-k/
2260
Chapter 311
Examples:
2261
Chapter 311. Number of paths from source to destination in a directed acyclic graph
Approach : Let f(u) be the number of ways one can travel from node u to destination vertex.
Hence, f(source) is required answer. As f(destination) = 1 here so there is just one path
from destination to itself. One can observe, f(u) depends on nothing other than the f values
of all the nodes which are possible to travel from u. It makes sense because the number of
different paths from u to the destination is the sum of all different paths from v1, v2, v3…
v-n to destination vertex where v1 to v-n are all the vertices that have a direct path from
vertex u. This approach, however, is too slow to be useful. Each function call branches out
into further calls, and that branches into further calls, until each and every path is explored
once.
The problem with this approach is the calculation of f(u) again and again each time the func-
tion is called with argument u. Since this problem exhibits both overlapping subproblems
and optimal substructure, dynamic programming is applicable here. In order to evaluate
f(u) for each u just once, evaluate f(v) for all v that can be visited from u before evaluating
f(u). This condition is satisfied by reverse topological sorted order of the nodes of the graph.
Below is the implementation of the above approach:
2262
Chapter 311. Number of paths from source to destination in a directed acyclic graph
{
queue<int> q;
// insert all vertices which
// don't have any parent.
for (int i = 0; i < n; i++)
if (!fre[i])
q.push(i);
vector<int> l;
// using kahn's algorithm
// for topological sorting
while (!q.empty()) {
int u = q.front();
q.pop();
// insert front element of queue to vector
l.push_back(u);
// go through all it's childs
for (int i = 0; i < v[u].size(); i++) {
fre[v[u][i]]--;
// whenever the freqency is zero then add
// this vertex to queue.
if (!fre[v[u][i]])
q.push(v[u][i]);
}
}
return l;
}
// Function that returns the number of paths
int numberofPaths(int source, int destination, int n, int fre[])
{
// make topological sorting
vector<int> s = topological_sorting(fre, n);
// to store required answer.
int dp[n] = { 0 };
// answer from destination
// to destination is 1.
dp[destination] = 1;
// traverse in reverse order
2263
Chapter 311. Number of paths from source to destination in a directed acyclic graph
Output:
Source
https://www.geeksforgeeks.org/number-of-paths-from-source-to-destination-in-a-directed-acyclic-graph/
2264
Chapter 312
Input: k = 12
mat[][] = { {1, 2, 3},
{4, 6, 5},
{3, 2, 1}
};
Output: 2
There are two paths with 12 coins
1 -> 2 -> 6 -> 2 -> 1
1 -> 2 -> 3 -> 5 -> 1
If (m == 0 and n == 0)
return 1 if mat[0][0] == k else return 0
Else:
pathCount(m, n, k) = pathCount(m-1, n, k - mat[m][n]) +
pathCount(m, n-1, k - mat[m][n])
2265
Chapter 312. Number of paths with exactly k coins
C++
// A Naive Recursive C++ program to count paths with exactly
// 'k' coins
#include <bits/stdc++.h>
#define R 3
#define C 3
using namespace std;
// Recursive function to count paths with sum k from
// (0, 0) to (m, n)
int pathCountRec(int mat[][C], int m, int n, int k)
{
// Base cases
if (m < 0 || n < 0) return 0;
if (m==0 && n==0) return (k == mat[m][n]);
// (m, n) can be reached either through (m-1, n) or
// through (m, n-1)
return pathCountRec(mat, m-1, n, k-mat[m][n]) +
pathCountRec(mat, m, n-1, k-mat[m][n]);
}
// A wrapper over pathCountRec()
int pathCount(int mat[][C], int k)
{
return pathCountRec(mat, R-1, C-1, k);
}
// Driver program
int main()
{
int k = 12;
int mat[R][C] = { {1, 2, 3},
{4, 6, 5},
{3, 2, 1}
};
cout << pathCount(mat, k);
return 0;
}
Python3
2266
Chapter 312. Number of paths with exactly k coins
PHP
<?php
// A Naive Recursive PHP program to
// count paths with exactly 'k' coins
$R = 3;
$C = 3;
// Recursive function to count paths
// with sum k from (0, 0) to (m, n)
function pathCountRec( $mat, $m, $n, $k)
{
2267
Chapter 312. Number of paths with exactly k coins
// Base cases
if ($m < 0 or $n < 0)
return 0;
if ($m == 0 and $n == 0)
return ($k == $mat[$m][$n]);
// (m, n) can be reached either
// through (m-1, n) or through
// (m, n-1)
return pathCountRec($mat, $m - 1,
$n, $k - $mat[$m][$n])
+ pathCountRec($mat, $m,
$n - 1, $k - $mat[$m][$n]);
}
// A wrapper over pathCountRec()
function pathCount($mat, $k)
{
global $R, $C;
return pathCountRec($mat, $R-1,
$C-1, $k);
}
// Driver program
$k = 12;
$mat = array(array(1, 2, 3),
array(4, 6, 5),
array(3, 2, 1) );
echo pathCount($mat, $k);
// This code is contributed by anuj_67.
?>
Output:
The time complexity of above solution recursive is exponential. We can solve this problem
in Pseudo Polynomial Time (time complexity is dependent on numeric value of input) using
Dynamic Programming. The idea is to use a 3 dimensional table dp[m][n][k] where m is row
number, n is column number and k is number of coins. Below is Dynamic Programming
based C++ implementation.
2268
Chapter 312. Number of paths with exactly k coins
Output:
2269
Chapter 312. Number of paths with exactly k coins
Source
https://www.geeksforgeeks.org/number-of-paths-with-exactly-k-coins/
2270
Chapter 313
Input : N = 3, K = 1
Output : 2
Explanation :
Total Permutation of first N number,
123, 132, 213, 231, 312, 321
Permutation with 1 inversion : 132 and 213
Input : N = 4, K = 2
Output : 5
A Naïve way to solve this problem is noting down all permutation then checking count of
inversion in them but iterating through permutation itself will take O(N!) time, which is
too large.
We can solve this problem using dynamic programming approach. Below is recursive for-
mula.
If N is 0, Count(0, K) = 0
2271
Chapter 313. Number of permutation with K inversions
In general case,
If we have N number and require K inversion,
Count(N, K) = Count(N - 1, K) +
Count(N – 1, K - 1) +
Count(N – 1, K – 2) +
.... +
Count(N – 1, 0)
C++
2272
Chapter 313. Number of permutation with K inversions
return memo[N][K];
// calling recursively all subproblem
// of permutation size N - 1
int sum = 0;
for (int i = 0; i <= K; i++)
{
// Call recursively only
// if total inversion
// to be made are less
// than size
if (i <= N - 1)
sum += numberOfPermWithKInversion(N - 1,
K - i);
}
// store result into memo
memo[N][K] = sum;
return sum;
}
// Driver code
int main()
{
int N = 4;
int K = 2;
cout << numberOfPermWithKInversion(N, K);
return 0;
}
Java
2273
Chapter 313. Number of permutation with K inversions
Python3
# Python3 program to find number of permutation
2274
Chapter 313. Number of permutation with K inversions
Output:
2275
Chapter 313. Number of permutation with K inversions
Improved By : jit_t
Source
https://www.geeksforgeeks.org/number-of-permutation-with-k-inversions/
2276
Chapter 314
Number of subsequences in a
string divisible by n
This problem can be recursively defined. Let remainder of a string with value x be ‘r’ when
divided with n. Adding one more character to this string changes its remainder to (r*10 +
newdigit) % n. For every new character, we have two choices, either add it in all current
subsequences or ignore it. Thus, we have an optimal substructure. Following shows the
brute force version of this:
2277
Chapter 314. Number of subsequences in a string divisible by n
int ans = 0;
return ans;
}
The above recursive solution has overlapping subproblems as shown in below recursion tree.
2278
Chapter 314. Number of subsequences in a string divisible by n
Output:
2279
Chapter 314. Number of subsequences in a string divisible by n
Source
https://www.geeksforgeeks.org/number-subsequences-string-divisible-n/
2280
Chapter 315
Input : abbc
Output : 3
Subsequences are abc, abc and abbc
Input : abcabc
Output : 7
Subsequences are abc, abc, abbc, aabc
abcc, abc and abc
Asked in : Amazon
We traverse given string. For every character encounter, we do following:
1) Initialize counts of different subsequences caused by different combination of ‘a’. Let this
count be aCount.
2) Initialize counts of different subsequences caused by different combination of ‘b’. Let this
count be bCount.
2281
Chapter 315. Number of subsequences of the form a^i b^j c^k
3) Initialize counts of different subsequences caused by different combination of ‘c’. Let this
count be cCount.
4) Traverse all characters of given string. Do following for current character s[i]
If current character is ‘a’, then there are following possibilities :
a) Current character begins a new subsequence.
b) Current character is part of aCount subsequences.
c) Current character is not part of aCount subsequences.
Therefore we do aCount = (1 + 2 * aCount);
If current character is ‘b’, then there are following possibilities :
a) Current character begins a new subsequence of b’s with aCount subsequences.
b) Current character is part of bCount subsequences.
c) Current character is not part of bCount subsequences.
Therefore we do bCount = (aCount + 2 * bCount);
If current character is ‘c’, then there are following possibilities :
a) Current character begins a new subsequence of c’s with bCount subsequences.
b) Current character is part of cCount subsequences.
c) Current character is not part of cCount subsequences.
Therefore we do cCount = (bCount + 2 * cCount);
5) Finally we return cCount;
Below is the implementation of above idea :
C++
2282
Chapter 315. Number of subsequences of the form a^i b^j c^k
// Traverse all characters of given string
for (unsigned int i=0; i<s.size(); i++)
{
/* If current character is 'a', then
there are following possibilities :
a) Current character begins a new
subsequence.
b) Current character is part of aCount
subsequences.
c) Current character is not part of
aCount subsequences. */
if (s[i] == 'a')
aCount = (1 + 2 * aCount);
/* If current character is 'b', then
there are following possibilities :
a) Current character begins a new
subsequence of b's with aCount
subsequences.
b) Current character is part of bCount
subsequences.
c) Current character is not part of
bCount subsequences. */
else if (s[i] == 'b')
bCount = (aCount + 2 * bCount);
/* If current character is 'c', then
there are following possibilities :
a) Current character begins a new
subsequence of c's with bCount
subsequences.
b) Current character is part of cCount
subsequences.
c) Current character is not part of
cCount subsequences. */
else if (s[i] == 'c')
cCount = (bCount + 2 * cCount);
}
return cCount;
}
// Driver code
int main()
{
string s = "abbc";
cout << countSubsequences(s) << endl;
2283
Chapter 315. Number of subsequences of the form a^i b^j c^k
return 0;
}
Java
2284
Chapter 315. Number of subsequences of the form a^i b^j c^k
C#
2285
Chapter 315. Number of subsequences of the form a^i b^j c^k
2286
Chapter 315. Number of subsequences of the form a^i b^j c^k
PHP
<?php
// PHP program to count subsequences
// of the form a^i b^j c^k
// Returns count of subsequences
// of the form a^i b^j c^k
function countSubsequences($s)
{
// Initialize counts of
// different subsequences
// caused by different
// combination of 'a'
$aCount = 0;
// Initialize counts of
// different subsequences
// caused by different
// combination of 'a' and
// different combination of 'b'
$bCount = 0;
// Initialize counts of
// different subsequences
// caused by different
// combination of 'a', 'b'
// and 'c'.
$cCount = 0;
// Traverse all characters
2287
Chapter 315. Number of subsequences of the form a^i b^j c^k
2288
Chapter 315. Number of subsequences of the form a^i b^j c^k
?>
Output:
Source
https://www.geeksforgeeks.org/number-subsequences-form-ai-bj-ck/
2289
Chapter 316
A simple solution is to generate all possible subsets. For every subset, compute its sum
and if sum is multiiple of m, increment result by 1. Time complexity of this approach is
O(2len ) where len is length of input array.
An efficient solution (for small values) is based on Dynamic Programming solution of
subset sum problem. We make a 2D array of size sum x n.
2290
Chapter 316. Number of subsets with sum divisible by m
#include <bits/stdc++.h>
using namespace std;
// Use Dynamic Programming to find
// sum of subsequences.
int sumSubSequence(vector<int> arr, int len, int m)
{
// Find sum pf array elements
int sum = 0;
for (auto x : arr)
sum += x;
// dp[i][j] would be > 0 if arr[0..i-1] has
// a subsequence with sum equal to j.
vector<vector<int> > dp(len + 1, vector<int>(sum + 1, 0));
// There is always sum equals zero
for (int i = 0; i <= len; i++)
dp[i][0]++;
// Fill up the dp table
for (int i = 1; i <= len; i++) {
dp[i][arr[i - 1]]++;
for (int j = 1; j <= sum; j++) {
if (dp[i - 1][j] > 0) {
dp[i][j]++;
dp[i][j + arr[i - 1]]++;
}
}
}
// Initialize the counter
int count = 0;
for (int j = 1; j <= sum; j++)
// Check if the sum exists
if (dp[len][j] > 0)
// check sum is divisible by m
if (j % m == 0)
count += dp[len][j];
return count;
}
// Driver Code
2291
Chapter 316. Number of subsets with sum divisible by m
int main()
{
vector<int> arr{ 1, 2, 3 };
int m = 3;
int len = arr.size();
cout << sumSubSequence(arr, len, m) << endl;
return 0;
}
Output:
Time complexity of the above approach is O(len*sum) where len is the size of the array
and sum is the sum of all the integers in the array.
Source
https://www.geeksforgeeks.org/number-of-subsets-with-sum-divisible-by-m/
2292
Chapter 317
A number is divisible by 3 if sum of its digits is divisible by 3. And the number is divisible
by 8 if last three digits are divisible by 8.
Now, the idea is to store the prefix sum of the string i.e count of prefixes such that sum of
the digits of the prefix modulo 3 is either 0, 1, 2. Next we iterate over the string and for
each position i, count the number of substrings ending at i and divisible by 8. From this
value, we subtract the number of substrings ending at i and divisible by 3.
We define a |S| X 3 size 2D array, |S| is size of string, say dp[i][j].
dp[i][j] can be define as at any index i, number of substring starting from index 0 to index
i having output j
when digits from index 0 are added upto index i and modulo 3. Therefore 0 <= j <= 2,
since modulo 3. Now, we will iterate over string and check each one digit number, two
digit number and three digit number which are divisible by 8. For one digit, just check if
character at index is 8 or not. For two digit, check whether it is divisible by 8 and not
2293
Chapter 317. Number of substrings divisible by 8 but not by 3
divisible by 3. For three digit, form the number and check if it is divisible by 8 or not. If
the number is divisible then last three digits must be divisible by 8. So all the substring
ending at this index must be divisible by 8 i.e (i-3) substrings. But it will also contain those
substring which are divisible by 3, so simply remove them using dp[i][j].
C/C++
2294
Chapter 317. Number of substrings divisible by 8 but not by 3
// Since single digit 8 is divisible
// by 8 and not by 3.
if (dig == 8)
ans++;
// Taking two digit number.
if (i-2 >= 0)
{
dprev = int(s[i-2])-48; // 10th position
value = dprev*10 + dig; // Complete 2 digit
// number
if ((value%8 == 0) && (value%3 != 0))
ans++;
}
// Taking 3 digit number.
if (i-3 >= 0)
{
dprev2 = int(s[i-3])-48; // 100th position
dprev = int(s[i-2])-48; // 10th position
// Complete 3 digit number.
value = dprev2*100 + dprev*10 + dig;
if (value%8 != 0)
continue;
// If number formed is divisible by 8 then
// last 3 digits are also divisible by 8.
// Then all the substring ending at this
// index is divisible.
ans += (i-2);
// But those substring also contain number
// which are not divisible by 3 so
// remove them.
ans -= (dp[i-3][sum[i]]);
}
}
return ans;
}
// Driven Program
int main()
{
2295
Chapter 317. Number of substrings divisible by 8 but not by 3
Java
2296
Chapter 317. Number of substrings divisible by 8 but not by 3
2297
Chapter 317. Number of substrings divisible by 8 but not by 3
{
String str = "6564525600";
int len = str.length();
System.out.println(count(str, len));
}
}
// Contributed by Pramod Kumar
C#
2298
Chapter 317. Number of substrings divisible by 8 but not by 3
2299
Chapter 317. Number of substrings divisible by 8 but not by 3
Output:
15
Improved By : parashar
Source
https://www.geeksforgeeks.org/number-substrings-divisible-8-not-3/
2300
Chapter 318
Number of ways a convex polygon of n+2 sides can split into triangles by connecting vertices
- GeeksforGeeks
Given a convex polygon with n+2 sides. The task is to calculate the number of ways in
which triangles can be formed by connecting vertices with non-crossing line segments.
Examples:
Input: n = 1
Output: 1
It is already a triangle so it can only be formed in 1 way.
Input: n = 2
Output: 2
It can be cut into 2 triangles by using either pair of opposite vertices.
2301
Chapter 318. Number of ways a convex polygon of n+2 sides can split into triangles by
connecting vertices
The above problem is an application of a catalan numbers. So, the task is to only find the
n’th Catalan Number. First few catalan numbers are 1 1 2 5 14 42 132 429 1430 4862, …
(considered from 0th number)
Below is the program to find Nth catalan number:
C++
2302
Chapter 318. Number of ways a convex polygon of n+2 sides can split into triangles by
connecting vertices
}
// A Binomial coefficient based function
// to find nth catalan
// number in O(n) time
unsigned long int catalan(unsigned int n)
{
// Calculate value of 2nCn
unsigned long int c = binomialCoeff(2 * n, n);
// return 2nCn/(n+1)
return c / (n + 1);
}
// Driver code
int main()
{
int n = 3;
cout << catalan(n) << endl;
return 0;
}
Java
2303
Chapter 318. Number of ways a convex polygon of n+2 sides can split into triangles by
connecting vertices
}
return res;
}
// A Binomial coefficient
// based function to find
// nth catalan number in
// O(n) time
static long catalan( int n)
{
// Calculate value of 2nCn
long c = binomialCoeff(2 * n, n);
// return 2nCn/(n+1)
return c / (n + 1);
}
// Driver code
public static void main(String[] args)
{
int n = 3;
System.out.println(catalan(n));
}
}
// This code is contributed
// by Arnab Kundu
C#
2304
Chapter 318. Number of ways a convex polygon of n+2 sides can split into triangles by
connecting vertices
// Calculate value of
// [n*(n-1)*---*(n-k+1)] /
// [k*(k-1)*---*1]
for (int i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
// A Binomial coefficient
// based function to find
// nth catalan number in
// O(n) time
static long catalan( int n)
{
// Calculate value of 2nCn
long c = binomialCoeff(2 * n, n);
// return 2nCn/(n+1)
return c / (n + 1);
}
// Driver code
public static void Main()
{
int n = 3;
Console.WriteLine(catalan(n));
}
}
// This code is contributed
// by Subhadeep
PHP
$n – $k)
$k = $n – $k;
// Calculate value of
// [n*(n-1)*—*(n-k+1)] /
// [k*(k-1)*—*1]
for ($i = 0; $i < $k; ++$i) { $res *= ($n - $i); $res /= ($i + 1); } return $res; } // A Binomial
coefficient based // function to find nth catalan // number in O(n) time function catalan($n)
{ // Calculate value of 2nCn $c = binomialCoeff(2 * $n, $n); // return 2nCn/(n+1) return
$c / ($n + 1); } // Driver code $n = 3; echo catalan($n); // This code is contributed // by
2305
Chapter 318. Number of ways a convex polygon of n+2 sides can split into triangles by
connecting vertices
chandan_jnu. ?>
Output:
Source
https://www.geeksforgeeks.org/number-of-ways-a-convex-polygon-of-n2-sides-can-split-into-triangles-by-connecting
2306
Chapter 319
Input : N = 3
k1 = 1 k2 = 2
Output : 2
Explanation :
Possible ways to arrange are,
k1, k2, k2
k2, k1, k2
Input : N = 4
k1 = 2 k2 = 2
Output : 3
Explanation :
Possible ways to arrange are,
k1, k2, k1, k2
k1, k1, k2, k2
k2, k1, k1, k2
We can solve this problem using dynamic programming. Let dp[i] stores the number of ways
to arrange first i colored items. For one colored item answer will be one because there is
2307
Chapter 319. Number of ways to arrange N items under given constraints
only one way. Now Let’s assume all items are in a sequence. Now, to go from dp[i] to dp[i
+ 1], we need to put at least one item of color (i + 1) at the very end, but the other items
of color (i + 1) can go anywhere in the sequence. The number of ways to arrange the item
of color (i + 1) is combination of (k1 + k2 .. + ki + k(i + 1) – 1) over (k(i + 1) – 1) which
can be represented as (k1 + k2 .. + ki + k(i + 1) – 1)C(k(i + 1) – 1). In this expression
we subtracted one because we need to put one item at the very end.
In below code, first we have calculated the combination values, you can read more about
that from here. After that we looped over all different color and calculated the final value
using above relation.
2308
Chapter 319. Number of ways to arrange N items under given constraints
Output:
Source
https://www.geeksforgeeks.org/number-of-ways-to-arrange-n-items-under-given-constraints/
2309
Chapter 320
Input : n = 3
Output : Assume the integers are 1, 2, 3.
Then the 2 possible max heaps are:
3
/ \
1 2
3
/ \
2 1
Input : n = 4
Output : Assume the integers are 1, 2, 3, 4.
Then the 3 possible max heaps are:
4
/ \
3 2
/
1
4
/ \
2 3
2310
Chapter 320. Number of ways to form a heap with n distinct integers
/
1
4
/ \
3 1
/
2
Since there is only one element as the root, it must be the largest number. Now we have n-1
remaining elements. The main observation here is that because of the max heap properties,
the structure of the heap nodes will remain the same in all instances, but only the values
in the nodes will change.
Assume there are l elements in the left sub-tree and r elements in the right sub-tree.
Now for the root, l + r = n-1. From this we can see that we can choose any l of the
remaining n-1 elements for the left sub-tree as they are all smaller than the root.
We know the there are ways to do this. Next for each instance of these, we can
have many heaps with l elements and for each of those we can have many heaps with r
elements. Thus we can consider them as subproblems and recur for the final answer as:
heap h = . Also the maximum number of elements that can be present in the h
th level of any heap, m = , where the root is at the 0th level. Moreover the number of
elements actually present in the last level of the heap p = n – ( – 1). (since
number of nodes present till the penultimate level). Thus, there can be two cases: when
the last level is more than or equal to half-filled:
l= – 1, if p >= m / 2
(or) the last level is less than half-filled:
values of . Similarly if we look at the recursion tree for the optimal substructure
recurrence formed above, we can see that it also has overlapping subproblems property,
hence can be solved using dynamic programming:
T(7)
2311
Chapter 320. Number of ways to form a heap with n distinct integers
/ \
T(3) T(3)
/ \ / \
T(1) T(1) T(1) T(1)
2312
Chapter 320. Number of ways to form a heap with n distinct integers
// max number of elements that can be present in the
// hth level of any heap
int numh = (1 << h); //(2 ^ h)
// number of elements that are actually present in
// last level(hth level)
// (2^h - 1)
int last = n - ((1 << h) - 1);
// if more than half-filled
if (last >= (numh / 2))
return (1 << h) - 1; // (2^h) - 1
else
return (1 << h) - 1 - ((numh / 2) - last);
}
// find maximum number of heaps for n
int numberOfHeaps(int n)
{
if (n <= 1)
return 1;
if (dp[n] != -1)
return dp[n];
int left = getLeft(n);
int ans = (choose(n - 1, left) * numberOfHeaps(left)) *
(numberOfHeaps(n - 1 - left));
dp[n] = ans;
return ans;
}
// function to initialize arrays
int solve(int n)
{
for (int i = 0; i <= n; i++)
dp[i] = -1;
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++)
nck[i][j] = -1;
int currLog2 = -1;
int currPower2 = 1;
// for each power of two find logarithm
for (int i = 1; i <= n; i++) {
2313
Chapter 320. Number of ways to form a heap with n distinct integers
if (currPower2 == i) {
currLog2++;
currPower2 *= 2;
}
log2[i] = currLog2;
}
return numberOfHeaps(n);
}
// driver function
int main()
{
int n = 10;
cout << solve(n) << endl;
return 0;
}
Output:
3360
Source
https://www.geeksforgeeks.org/number-ways-form-heap-n-distinct-integers/
2314
Chapter 321
Input: N = 4, M = 3, X = 2
Output: 3
The following arrays are possible:
1) 2, 1, 2, 1
2) 2, 1, 3, 1
3) 2, 3, 2, 1
Input: N = 2, M = 3, X = 2
Output: 1
The only possible array is: 2, 1
Approach: The problem can be solved using Dynamic Programming. Let, f(i) represent
the number of ways to form the array till the ith index, such that every consecutive element
of the array is distinct. Let f(i, One) represent the number of ways to form the array till
the i-th index such that every consecutive element of the array is distinct and arri = 1.
Similarly, let f(i, Non-One) represent the number of ways to form the array till the ith
index, such that every consecutive element of the array is distinct and arri is not equal to 1.
The following recurrence is formed:
2315
Chapter 321. Number of ways to form an array with distinct adjacent elements
which means that the number of ways to form the array till the ith index with arrayi not
equal to 1 is formed using two cases:
1. If the number at arrayi – 1 is 1, then opt one number out of (M – 1) options to place
at the ith index, since arrayi is not equal to 1.
2. If the number at arrayi – 1 is not 1, then we need to opt one number out of (M – 2)
options, since arrayi is not equal to 1 and arrayi � arrayi – 1 .
Similarly, f(i, One) = f(i – 1, Non-One), since the number of ways to form the array
till the ith index with arrayi = 1, is same as number of ways to form the array till the (i –
1)th index with arrayi – 1 � 1, thus at the ith index there is only one option. At the end the
required answer if f(N, One) since arrayN needs to be equal to 1.
Below is the implementation of the above approach:
C++
2316
Chapter 321. Number of ways to form an array with distinct adjacent elements
dp[0][1] = 0;
}
// if the first element was 1 then at index 1,
// only non one integer can be placed thus
// there are M - 1 ways to place a non one integer
// at index 2 and 0 ways to place a 1 at the 2nd index
if (X == 1) {
dp[1][0] = 0;
dp[1][1] = M - 1;
}
// Else there is one way to place a one at
// index 2 and if a non one needs to be placed here,
// there are (M - 2) options, i.e
// neither the element at this index
// should be 1, neither should it be
// equal to the previous element
else {
dp[1][0] = 1;
dp[1][1] = (M - 2);
}
// Build the dp array in bottom up manner
for (int i = 2; i < N; i++) {
// f(i, one) = f(i - 1, non-one)
dp[i][0] = dp[i - 1][1];
// f(i, non-one) = f(i - 1, one) * (M - 1) +
// f(i - 1, non-one) * (M - 2)
dp[i][1] = dp[i - 1][0] * (M - 1) + dp[i - 1][1] * (M - 2);
}
// last element needs to be one, so return dp[n - 1][0]
return dp[N - 1][0];
}
// Driver Code
int main()
{
int N = 4, M = 3, X = 2;
cout << totalWays(N, M, X) << endl;
return 0;
}
2317
Chapter 321. Number of ways to form an array with distinct adjacent elements
Java
2318
Chapter 321. Number of ways to form an array with distinct adjacent elements
2319
Chapter 321. Number of ways to form an array with distinct adjacent elements
C#
2320
Chapter 321. Number of ways to form an array with distinct adjacent elements
2321
Chapter 321. Number of ways to form an array with distinct adjacent elements
dp[i - 1, 1] * (M - 2);
}
// last element needs to be
// one, so return dp[n - 1][0]
return dp[N - 1, 0];
}
// Driver Code
public static void Main ()
{
int N = 4, M = 3, X = 2;
Console.WriteLine(totalWays(N, M, X));
}
}
// This code is contributed
// by anuj_67.
PHP
<?php
// PHP program to count the
// number of ways to form
// arrays of N numbers such
// that the first and last
// numbers are fixed and all
// consecutive numbers are distinct
// Returns the total ways to
// form arrays such that every
// consecutive element is
// different and each element
// except the first and last
// can take values from 1 to M
function totalWays($N, $M, $X)
{
// define the dp[][] array
$dp = array(array());
// if the first element is 1
if ($X == 1)
{
// there is only one
// way to place a 1
// at the first index
2322
Chapter 321. Number of ways to form an array with distinct adjacent elements
$dp[0][0] = 1;
}
else
{
// the value at first
// index needs to be 1,
// thus there is no way
// to place a non-one integer
$dp[0][1] = 0;
}
// if the first element was
// 1 then at index 1, only
// non one integer can be
// placed thus there are M - 1
// ways to place a non one
// integer at index 2 and 0 ways
// to place a 1 at the 2nd index
if ($X == 1)
{
$dp[1][0] = 0;
$dp[1][1] = $M - 1;
}
// Else there is one way
// to place a one at index
// 2 and if a non one needs
// to be placed here, there
// are (M - 2) options, i.e
// neither the element at
// this index should be 1,
// neither should it be equal
// to the previous element
else
{
$dp[1][0] = 1;
$dp[1][1] = ($M - 2);
}
// Build the dp array
// in bottom up manner
for ($i = 2; $i <$N; $i++)
{
// f(i, one) =
// f(i - 1, non-one)
$dp[$i][0] = $dp[$i - 1][1];
2323
Chapter 321. Number of ways to form an array with distinct adjacent elements
// f(i, non-one) =
// f(i - 1, one) * (M - 1) +
// f(i - 1, non-one) * (M - 2)
$dp[$i][1] = $dp[$i - 1][0] *
($M - 1) +
$dp[$i - 1][1] *
($M - 2);
}
// last element needs to
// be one, so return dp[n - 1][0]
return $dp[$N - 1][0];
}
// Driver Code
$N = 4; $M = 3; $X = 2;
echo totalWays($N, $M, $X);
// This code is contributed
// by anuj_67.
?>
Output:
Source
https://www.geeksforgeeks.org/number-of-ways-to-form-an-array-with-distinct-adjacent-elements/
2324
Chapter 322
Let say for a given string A and string B, the length of their LCS is k. Let’s insert a
single character ‘c’ after the ith character in string A and denote the string formed after the
insertion as string Anew , which looks like:
Anew = A1, i . c . Ai + 1, n
2325
Chapter 322. Number of ways to insert a character to increase the LCS by one
where Ai, j denotes a substring of string A from the ith to the jth characters and ‘.’ denotes
a concatenation of two strings.
Let’s define knew to be the length of the LCS of Anew and B. Now we want to know if knew
= k + 1.
The crucial observation is that the newly inserted character ‘c’ must be a part of any common
subsequence of Anew and B having length > k. We know this because if there is any common
subsequence of Anew and B, this is a contradiction, because it would mean the length of the
LCS of A and B is > k.
Using the above observation, we can try the following approach. For each possible character
‘c’(there are 52 upper and lower case English letters and 10 arabic digits, so there are 62
possible characters to insert) and for every possible insertion possible i in String A (there
are |a| + 1 insertion positions), let’s try to insert ‘c’ after the ith character in string A and
match it with every occurance of ‘c’ in string B, we can try to match these ‘c’ characters
such that:
A1, i . c . Ai+1, n
A1, j-1 . c . Ai+1, m
Now, in order to check if such an insertion produces an LCS of length k + 1, it’s sufficienet
to check if the length of the LCS of A1, i and B1, j-1 plus the length of the LCS Ai+1, n
and Bj+1, m is equal to k. In this case, the lCS of Anew and B is k + 1 because there is
both a match between the fixed occurances of character ‘c’ and there is no longer common
subsequence between them.
If we can quickly get the length of the LCS between every two prefixes of A nad B as
well as between every two of their suffixes, we can compute the result. The length of the
LCS between their prefixes can be read from from a Dynamic Programming table used in
computing the LCS of string A and string B. In this method, dp[i][j] stores the length of
longest common subsequence of A, i and Bi, j . Similarly, the length of the LCS between their
suffixes can be read from an analogous dp tables which can be computed during computation
of the LCS of Areversed and Breversed where Sreversed denotes the reversed string S.
2326
Chapter 322. Number of ways to insert a character to increase the LCS by one
2327
Chapter 322. Number of ways to insert a character to increase the LCS by one
Output:
Source
https://www.geeksforgeeks.org/number-ways-insert-character-increase-lcs-one/
2328
Chapter 323
Input: N = 5, K = 3
Output: 5
To reach stair no-5 we can choose following combination of leaps:
11111
1112
122
113
23
Therefore the answer is 5.
Input: N = 29, K = 5
Output: 603
Let combo[i] be the number of ways to reach the i-th floor. Hence the number of ways to reach
combo[i] from combo[j] by taking a leap of i-j will be combo[i] += combo[j]. So iterate
for all possible leaps, and for each possible leaps keep adding the possible combinations to
the combo array. The final answer will be stored in combo[N].
Below is the implementation of the above approach.
C++
2329
Chapter 323. Number of ways to reach Nth floor by taking at-most K leaps
2330
Chapter 323. Number of ways to reach Nth floor by taking at-most K leaps
{
// N i the no of total stairs
// K is the value of the greatest leap
int N = 29;
int K = 5;
cout << solve(N, K);
solve(N, K);
return 0;
}
Java
2331
Chapter 323. Number of ways to reach Nth floor by taking at-most K leaps
if (j >= i)
{
// calculate the value and
// store in combo[j] to
// reuse it for next leap
// calculation for the
// jth stair
combo[j] += combo[j - i];
}
}
}
// returns the no of possible
// number of leaps to reach
// the top of building of
// n stairs
return combo[N];
}
// Driver Code
public static void main(String args[])
{
// N i the no of total stairs
// K is the value of the
// greatest leap
int N = 29;
int K = 5;
System.out.println(solve(N, K));
solve(N, K);
}
}
// This code is contributed
// by ankita_saini
C#
2332
Chapter 323. Number of ways to reach Nth floor by taking at-most K leaps
{
// elements of combo[] stores
// the no. of possible ways
// to reach it by all combinations
// of k leaps or less
int[] combo;
combo = new int[50];
// assuming leap 0 exist
// and assigning its value
// to 1 for calculation
combo[0] = 1;
// loop to iterate over all
// possible leaps upto k;
for (int i = 1; i <= K; i++)
{
// in this loop we count all
// possible leaps to reach
// the jth stair with the
// help of ith leap or less
for (int j = 0; j <= N; j++)
{
// if the leap is not
// more than the i-j
if (j >= i)
{
// calculate the value and
// store in combo[j] to
// reuse it for next leap
// calculation for the
// jth stair
combo[j] += combo[j - i];
}
}
}
// returns the no of possible
// number of leaps to reach
// the top of building of
// n stairs
return combo[N];
}
2333
Chapter 323. Number of ways to reach Nth floor by taking at-most K leaps
// Driver Code
public static void Main()
{
// N i the no of total stairs
// K is the value of the
// greatest leap
int N = 29;
int K = 5;
Console.WriteLine(solve(N, K));
solve(N, K);
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
PHP
<?php
error_reporting(0);
// PHP program to reach N-th
// stair by taking a maximum
// of K leap
function solve($N, $K)
{
// elements of combo[] stores
// the no of possible ways to
// reach it by all combinations
// of k leaps or less
$combo[$N + 1] = array();
// assuming leap 0 exist and
// assigning its value to 1
// for calculation
$combo[0] = 1;
// loop to iterate over all
// possible leaps upto k;
for ($i = 1; $i <= $K; $i++)
{
// in this loop we count
// all possible leaps to
// reach the jth stair with
// the help of ith leap or less
for ($j = 0; $j <= $N; $j++)
2334
Chapter 323. Number of ways to reach Nth floor by taking at-most K leaps
{
// if the leap is not
// more than the i-j
if ($j >= $i)
{
// calculate the value and
// store in combo[j]
// to reuse it for next leap
// calculation for the jth stair
$combo[$j] += $combo[$j - $i];
}
}
}
// returns the no of possible
// number of leaps to reach
// the top of building of n stairs
return $combo[$N];
}
// Driver Code
// N i the no of total stairs
// K is the value of the greatest leap
$N = 29;
$K = 5;
echo solve($N, $K);
solve($N, $K);
// This code is contributed
// by Akanksha Rai(Abby_akku)
?>
Output:
603
2335
Chapter 323. Number of ways to reach Nth floor by taking at-most K leaps
Source
https://www.geeksforgeeks.org/number-of-ways-to-reach-nth-floor-by-taking-at-most-k-leaps/
2336
Chapter 324
Input : n = 12, k = 1
Output : 0
Input : n = 13, k = 3
Output : 2
Explanation : 2 + 3 + 8, 3 + 5 + 5.
Approach: The Fibonacci series is f(0)=1, f(1)=2 and f(i)=f(i-1)+f(i-2) for i>1. Let’s
suppose F(x, k, n) be the number of ways to form the sum x using exactly k numbers
from f(0), f(1), …f(n-1). To find a recurrence for F(x, k, n), notice that there are two cases:
whether f(n-1) in the sum or not.
• If f(n-1) is not in the sum, then x is formed as a sum using exactly k numbers
from f(0), f(1), …, f(n-2).
• If f(n-1) is in the sum, then the remaining x-f(n-1) is formed using exactly k-
1 numbers from f(0), f(1), …, f(n-1). (Notice that f(n-1) is still included because
duplicate numbers are allowed.).
2337
Chapter 324. Number of ways to represent a number as sum of k fibonacci numbers
Base cases:
• If k=0, then there are zero numbers from the series, so the sum can only be 0. Hence,
F(0, 0, n)=1.
• F(x, 0, n)=0, if x is not equals to 0.
Also, there are other cases that make F(x, k, n)=0, like the following:
• If k>0 and x=0 because having at least one positive number must result in a positive
sum.
• If k>0 and n=0 because there’s no possible choice of numbers left.
• If x<0 because there’s no way to form a negative sum using a finite number of non-
negative numbers.
#include <bits/stdc++.h>
using namespace std;
// to store fibonacci numbers
// 42 second number in fibonacci series
// largest possible integer
int fib[43] = { 0 };
// Function to generate fibonacci series
void fibonacci()
{
fib[0] = 1;
fib[1] = 2;
for (int i = 2; i < 43; i++)
fib[i] = fib[i - 1] + fib[i - 2];
}
// Recursive function to return the
// number of ways
int rec(int x, int y, int last)
{
// base condition
if (y == 0) {
if (x == 0)
return 1;
return 0;
}
int sum = 0;
2338
Chapter 324. Number of ways to represent a number as sum of k fibonacci numbers
Output:
Source
https://www.geeksforgeeks.org/number-of-ways-to-represent-a-number-as-sum-of-k-fibonacci-numbers/
2339
Chapter 325
Padovan Sequence
2340
Chapter 325. Padovan Sequence
Examples:
C++
2341
Chapter 325. Padovan Sequence
}
/* Driver Program */
int main()
{
int n = 12;
cout << pad(n);
return 0;
}
Java
2342
Chapter 325. Padovan Sequence
Python
C#
2343
Chapter 325. Padovan Sequence
pCurr = pNext;
}
return pNext;
}
/* Driver Program */
public static void Main()
{
int n = 12;
Console.WriteLine(pad(n));
}
}
/*This code is contributed by vt_m.*/
PHP
<?php
// PHP program to find n'th
// term in Padovan Sequence
// using Dynamic Programming
// Function to calculate
// padovan number P(n)
function pad($n)
{
// 0th ,1st and 2nd number
// of the series are 1
$pPrevPrev = 1; $pPrev = 1;
$pCurr = 1; $pNext = 1;
for ($i = 3; $i <= $n; $i++)
{
$pNext = $pPrevPrev + $pPrev;
$pPrevPrev = $pPrev;
$pPrev = $pCurr;
$pCurr = $pNext;
}
return $pNext;
}
// Driver Code
$n = 12;
echo(pad($n));
2344
Chapter 325. Padovan Sequence
// This code is contributed by Ajit.
?>
Output:
21
Improved By : jit_t
Source
https://www.geeksforgeeks.org/padovan-sequence/
2345
Chapter 326
Input : n = 2 k = 4
Output : 16
We have 4 colors and 2 posts.
Ways when both posts have same color : 4
Ways when both posts have diff color :
4*(choices for 1st post) * 3(choices for
2nd post) = 12
Input : n = 3 k = 2
Output : 6
2346
Chapter 326. Painting Fence Algorithm
Following image depicts the 6 possible ways of painting 3 posts with 2 colors:
Consider the following image in which c, c’ and c” are respective colors of posts i, i-1 and i
-2.
2347
Chapter 326. Painting Fence Algorithm
for n = 1
diff = k, same = 0
total = k
for n = 2
diff = k * (k-1) //k choices for
first post, k-1 for next
same = k //k choices for common
color of two posts
total = k + k * (k-1)
for n = 3
diff = [k + k * (k-1)] * (k-1)
(k-1) choices for 3rd post
to not have color of 2nd
post.
same = k * (k-1)
c'' != c, (k-1) choices for it
2348
Chapter 326. Painting Fence Algorithm
Output:
Space optimization :
We can optimize above solution to use one variable instead of a table.
Below is the C++ implementation of the problem:
2349
Chapter 326. Painting Fence Algorithm
Output:
Source
https://www.geeksforgeeks.org/painting-fence-algorithm/
2350
Chapter 327
Input : 36 x 30
Output : 5
Explanation :
3 (squares of size 12x12) +
2 (squares of size 18x18)
Input : 4 x 5
Output : 5
Explanation :
1 (squares of size 4x4) +
4 (squares of size 1x1)
Asked in : Google
We have already discussed the Greedy approach to solve this problem in previous article.
But the previous approach doesn’t always work. For example, it fails for the above first test
case. So, in this article we solve this problem using Dynamic Programming.
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
2351
Chapter 327. Paper Cut into Minimum Number of Squares | Set 2
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.
2352
Chapter 327. Paper Cut into Minimum Number of Squares | Set 2
Explanation:
minimumSquare is a function which tries to split the rectangle at some position. The
function is called recursively for both parts. Try all possible splits and take the one with
minimum result. The base case is when both sides are equal i.e the input is already a square,
in which case the result is 1. We are trying to find the cut which is nearest to the center
which will lead us to our minimum result.
Assuming we have a rectangle with width is N and height is M.
C++
2353
Chapter 327. Paper Cut into Minimum Number of Squares | Set 2
*/
for (int i = 1;i<= m/2;i++)
{
// Calculating the minimum answer for the
// rectangles with width equal to n and length
// less than m for finding the cut point for
// the minimum answer
horizontal_min = min(minimumSquare(i, n) +
minimumSquare(m-i, n), horizontal_min);
}
for (int j = 1;j<= n/2;j++)
{
// Calculating the minimum answer for the
// rectangles with width less than n and
// length equal to m for finding the cut
// point for the minimum answer
vertical_min = min(minimumSquare(m, j) +
minimumSquare(m, n-j), vertical_min);
}
// Minimum of the vertical cut or horizontal
// cut to form a square is the answer
dp[m][n] = min(vertical_min, horizontal_min);
return dp[m][n];
}
// Driver code
int main()
{
int m = 30, n = 35;
cout << minimumSquare(m, n);
return 0;
}
// This code is contributed by Utkarsh Gupta
Java
2354
Chapter 327. Paper Cut into Minimum Number of Squares | Set 2
2355
Chapter 327. Paper Cut into Minimum Number of Squares | Set 2
minimumSquare(m, j) +
minimumSquare(m, n-j),
vertical_min);
}
// Minimum of the vertical cut or
// horizontal cut to form a square
// is the answer
dp[m][n] = Math.min(vertical_min,
horizontal_min);
return dp[m][n];
}
// Driver code
public static void main(String[] args)
{
int m = 30, n = 35;
System.out.println(minimumSquare(m, n));
}
}
// This code is contributed by Prerna Saini
C#
2356
Chapter 327. Paper Cut into Minimum Number of Squares | Set 2
2357
Chapter 327. Paper Cut into Minimum Number of Squares | Set 2
{
int m = 30, n = 35;
Console.WriteLine(minimumSquare(m, n));
}
}
// This code is contributed by anuj_67.
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/paper-cut-minimum-number-squares-set-2/
2358
Chapter 328
Partition a set into two subsets such that the difference of subset sums is minimum - Geeks-
forGeeks
Given a set of integers, the task is to divide it into two sets S1 and S2 such that the absolute
difference between their sums is minimum.
If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2 must
have n-m elements and the value of abs(sum(Subset1) – sum(Subset2)) should be minimum.
Example:
This problem is mainly an extension to the Dynamic Programming| Set 18 (Partition Prob-
lem).
Recursive Solution
The recursive approach is to generate all possible sums from all the values of array and to
check which solution is the most optimal one.
To generate sums we either include the i’th item in set 1 or don’t include, i.e., include in set 2.
2359
Chapter 328. Partition a set into two subsets such that the difference of subset sums is
minimum
Java
2360
Chapter 328. Partition a set into two subsets such that the difference of subset sums is
minimum
2361
Chapter 328. Partition a set into two subsets such that the difference of subset sums is
minimum
C#
2362
Chapter 328. Partition a set into two subsets such that the difference of subset sums is
minimum
// Compute total sum of elements
int sumTotal = 0;
for (int i = 0; i < n; i++)
sumTotal += arr[i];
// Compute result using recursive function
return findMinRec(arr, n, 0, sumTotal);
}
/* Driver program to test above function */
public static void Main()
{
int []arr = {3, 1, 4, 2, 2, 1};
int n = arr.Length;
Console.Write("The minimum difference"+
" between two sets is " +
findMin(arr, n));
}
}
// This code is contributed by nitin mittal.
Output:
Time Complexity:
Dynamic Programming
The problem can be solved using dynamic programming when the sum of the elements is not
too big. We can create a 2D array dp[n+1][sum+1] where n is number of elements in given
set and sum is sum of all elements. We can construct the solution in bottom up manner.
2363
Chapter 328. Partition a set into two subsets such that the difference of subset sums is
minimum
So
dp[n+1][sum+1] will be 1 if
1) The sum j is achieved including i'th item
2) The sum j is achieved excluding i'th item.
C++
2364
Chapter 328. Partition a set into two subsets such that the difference of subset sums is
minimum
2365
Chapter 328. Partition a set into two subsets such that the difference of subset sums is
minimum
Java
2366
Chapter 328. Partition a set into two subsets such that the difference of subset sums is
minimum
Output:
Time Complexity = O(n*sum) where n is number of elements and sum is sum of all elements.
Note that the above solution is in Pseudo Polynomial Time (time complexity is dependent
on numeric value of input).
This article is contributed by Abhiraj Smit. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/partition-a-set-into-two-subsets-such-that-the-difference-of-subset-sums-is-minimum
2367
Chapter 329
Partitioning into two contiguous element subarrays with equal sums - GeeksforGeeks
Given an array of n positive integers. Find a minimum positive element to be added to one
of the indexes in the array such that it can be partitioned into two contiguous sub arrays of
equal sums. Output the minimum element to be added and the position where it is to be
added. If multiple positions are possible then return the least one.
Examples:
Input : arr[] = { 5, 4 }
Output : 1 1
Explanation: We need to add 1 to 4 so that two sub arrays are {5},{5} hence
output is 1 1 (minimum element and it’s positon where it is to be added.
2368
Chapter 329. Partitioning into two contiguous element subarrays with equal sums
+ 1] (where suffixSum[i + 1] is the sum of array elements from (i + 1)th position to last
position).
For e.g.
arr 10 1 2 3 4
prefixSum 10 11 13 16 20
suffixSum 20 10 9 7 4
2369
Chapter 329. Partitioning into two contiguous element subarrays with equal sums
suffixSum[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--) {
// add current element to Sum
suffixSum[i] = suffixSum[i + 1] + arr[i];
}
// initialize the minimum element to be a large value
int min = suffixSum[0];
int pos;
for (int i = 0; i < n - 1; i++) {
// check for the minimum absolute difference
// between current prefix sum and the next
// suffix sum element
if (abs(suffixSum[i + 1] - prefixSum[i]) < min) {
min = abs(suffixSum[i + 1] - prefixSum[i]);
// if prefixsum has a greater value then position
// is the next element, else it's the same element.
if (suffixSum[i + 1] < prefixSum[i]) pos = i + 1;
else pos = i;
}
}
// return the data in struct.
result.element = min;
result.position = pos;
return result;
}
// Driver Code
int main()
{
int arr[] = { 10, 1, 2, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
struct data values;
values = findMinElement(arr, n);
cout << "Minimum element : " << values.element
<< endl << "Position : " << values.position;
return 0;
}
Output:
Minimum element : 0
2370
Chapter 329. Partitioning into two contiguous element subarrays with equal sums
Position : 0
Source
https://www.geeksforgeeks.org/partitioning-into-two-contiguous-element-subarray-with-equal-sums/
2371
Chapter 330
One interesting observation is, the only allowed moves are down and right, we need N-1
down moves and N-1 right moves to reach destination (bottom rightmost). So any path
from from top left corner to bottom right corner requires 2N – 1 cells. In average value,
denominator is fixed and we need to just maximize numerator. Therefore we basically need
to to find maximum sum path. Calculating maximum sum of path is a classic dynamic
programming problem, if dp[i][j] represents maximum sum till cell (i, j) from (0, 0) then at
each cell (i, j), we update dp[i][j] as below,
2372
Chapter 330. Path with maximum average value
Once we get maximum sum of all paths we will divide this sum by (2N – 1) and we will get
our maximum average.
C++
2373
Chapter 330. Path with maximum average value
{7, 3, 9}
};
printf("%f", maxAverageOfPath(cost, 3));
return 0;
}
Java
2374
Chapter 330. Path with maximum average value
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
C#
2375
Chapter 330. Path with maximum average value
Output:
2376
Chapter 330. Path with maximum average value
5.2
Source
https://www.geeksforgeeks.org/path-maximum-average-value/
2377
Chapter 331
Perfect Sum Problem (Print all subsets with given sum) - GeeksforGeeks
Given an array of integers and a sum, the task is to print all subsets of given array with
sum equal to given sum.
Examples:
Asked in Tesco
This problem is mainly an extension of Subset Sum Problem. Here we not only need to find
if there is a subset with given sum, but also need to print all subsets with given sum.
Like previous post, we build a 2D array dp[][] such that dp[i][j] stores true if sum j is possible
with array elements from 0 to i.
After filling dp[][], we recursively traverse it from dp[n-1][sum]. For cell being traversed, we
store path before reaching it and consider two possibilities for the element.
1) Element is included in current path.
2) Element is not included in current path.
2378
Chapter 331. Perfect Sum Problem (Print all subsets with given sum)
Whenever sum becomes 0, we stop the recursive calls and print current path.
Below is implementation of above idea.
C++
2379
Chapter 331. Perfect Sum Problem (Print all subsets with given sum)
2380
Chapter 331. Perfect Sum Problem (Print all subsets with given sum)
// Driver code
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
int sum = 10;
printAllSubsets(arr, n, sum);
return 0;
}
Java
2381
Chapter 331. Perfect Sum Problem (Print all subsets with given sum)
// If given sum can be achieved after ignoring
// current element.
if (dp[i-1][sum])
{
// Create a new vector to store path
ArrayList<Integer> b = new ArrayList<>();
b.addAll(p);
printSubsetsRec(arr, i-1, sum, b);
}
// If given sum can be achieved after considering
// current element.
if (sum >= arr[i] && dp[i-1][sum-arr[i]])
{
p.add(arr[i]);
printSubsetsRec(arr, i-1, sum-arr[i], p);
}
}
// Prints all subsets of arr[0..n-1] with sum 0.
static void printAllSubsets(int arr[], int n, int sum)
{
if (n == 0 || sum < 0)
return;
// Sum 0 can always be achieved with 0 elements
dp = new boolean[n][sum + 1];
for (int i=0; i<n; ++i)
{
dp[i][0] = true;
}
// Sum arr[0] can be achieved with single element
if (arr[0] <= sum)
dp[0][arr[0]] = true;
// Fill rest of the entries in dp[][]
for (int i = 1; i < n; ++i)
for (int j = 0; j < sum + 1; ++j)
dp[i][j] = (arr[i] <= j) ? (dp[i-1][j] ||
dp[i-1][j-arr[i]])
: dp[i - 1][j];
if (dp[n-1][sum] == false)
{
System.out.println("There are no subsets with" +
" sum "+ sum);
return;
2382
Chapter 331. Perfect Sum Problem (Print all subsets with given sum)
}
// Now recursively traverse dp[][] to find all
// paths from dp[n-1][sum]
ArrayList<Integer> p = new ArrayList<>();
printSubsetsRec(arr, n-1, sum, p);
}
//Driver Program to test above functions
public static void main(String args[])
{
int arr[] = {1, 2, 3, 4, 5};
int n = arr.length;
int sum = 10;
printAllSubsets(arr, n, sum);
}
}
//This code is contributed by Sumit Ghosh
Output :
4 3 2 1
5 3 2
5 4 1
Source
https://www.geeksforgeeks.org/perfect-sum-problem-print-subsets-given-sum/
2383
Chapter 332
Permutation Coefficient
P(10, 2) = 90
P(10, 3) = 720
P(10, 0) = 1
P(10, 1) = 10
The coefficient can also be computed recursively using the below recursive formula:
2384
Chapter 332. Permutation Coefficient
If we observe closely, we can analyze that the problem has overlapping substructure, hence
we can apply dynamic programming here. Below is a program implementing the same idea.
2385
Chapter 332. Permutation Coefficient
int n = 10, k = 2;
printf("Value of P(%d, %d) is %d ",
n, k, permutationCoeff(n, k));
return 0;
}
Java
2386
Chapter 332. Permutation Coefficient
}
// Driver Code
public static void main(String args[])
{
int n = 10, k = 2;
System.out.println("Value of P( " + n + ","+ k +")" +
" is " + permutationCoeff(n, k) );
}
}
// This code is contributed by Nikita Tiwari.
Python3
2387
Chapter 332. Permutation Coefficient
# Driver Code
n = 10
k = 2
print("Value fo P(", n, ", ", k, ") is ",
permutationCoeff(n, k), sep = "")
# This code is contributed by Soumen Ghosh.
C#
2388
Chapter 332. Permutation Coefficient
}
return P[n,k];
}
// Driver Code
public static void Main()
{
int n = 10, k = 2;
Console.WriteLine("Value of P( " + n +
","+ k +")" + " is " +
permutationCoeff(n, k) );
}
}
// This code is contributed by anuj_67..
PHP
<?php
// A Dynamic Programming based
// solution that uses table P[][]
// to calculate the Permutation
// Coefficient
// Returns value of Permutation
// Coefficient P(n, k)
function permutationCoeff( $n, $k)
{
$P = array(array());
// Caculate value of Permutation
// Coefficient in bottom up manner
for($i = 0; $i <= $n; $i++)
{
for($j = 0; $j <= min($i, $k); $j++)
{
// Base Cases
if ($j == 0)
$P[$i][$j] = 1;
// Calculate value using
// previosly stored values
else
$P[$i][$j] = $P[$i - 1][$j] +
($j * $P[$i - 1][$j - 1]);
// This step is important
2389
Chapter 332. Permutation Coefficient
Output :
Value of P(10, 2) is 90
Here as we can see the time complexity is O(n*k) and space complexity is O(n*k) as the
program uses an auxiliary matrix to store the result.
Can we do it in O(n) time ?
Let us suppose we maintain a single 1D array to compute the factorials up to n. We can
use computed factorial value and apply the formula P(n, k) = n! / (n-k)!. Below is a
program illustrating the same concept.
2390
Chapter 332. Permutation Coefficient
Java
2391
Chapter 332. Permutation Coefficient
System.out.println("Value of"
+ " P( " + n + ", " + k + ") is "
+ permutationCoeff(n, k) );
}
}
// This code is contributed by anuj_67.
Python3
C#
2392
Chapter 332. Permutation Coefficient
// Returns value of Permutation
// Coefficient P(n, k)
static int permutationCoeff(int n,
int k)
{
int []fact = new int[n+1];
// base case
fact[0] = 1;
// Caculate value
// factorials up to n
for (int i = 1; i <= n; i++)
fact[i] = i * fact[i - 1];
// P(n,k) = n! / (n - k)!
return fact[n] / fact[n - k];
}
// Driver Code
static public void Main ()
{
int n = 10, k = 2;
Console.WriteLine("Value of"
+ " P( " + n + ", " + k + ") is "
+ permutationCoeff(n, k) );
}
}
// This code is contributed by anuj_67.
PHP
<?php
// A O(n) Solution that
// uses table fact[] to
// calculate the Permutation
// Coefficient
// Returns value of Permutation
// Coefficient P(n, k)
function permutationCoeff($n, $k)
{
$fact = array();
// base case
$fact[0] = 1;
2393
Chapter 332. Permutation Coefficient
// Calculate value
// factorials up to n
for ($i = 1; $i <= $n; $i++)
$fact[$i] = $i * $fact[$i - 1];
// P(n,k)= n!/(n-k)!
return $fact[$n] / $fact[$n - $k];
}
// Driver Code
$n = 10;
$k = 2;
echo"Value of P(",$n," ", $k,") is ",
permutationCoeff($n, $k) ;
// This code is contributed by anuj_67.
?>
Output :
Value of P(10, 2) is 90
2394
Chapter 332. Permutation Coefficient
// Driver Code
int main()
{
int n = 10, k = 2;
cout << "Value of P(" << n << ", " << k
<< ") is " << PermutationCoeff(n, k);
return 0;
}
Java
2395
Chapter 332. Permutation Coefficient
Python3
C#
2396
Chapter 332. Permutation Coefficient
}
int coeff = Fn / Fk;
return coeff;
}
// Driver Code
public static void Main()
{
int n = 10, k = 2;
Console.WriteLine("Value of P( "
+ n + "," + k +") is "
+ PermutationCoeff(n, k) );
}
}
// This code is contributed by anuj_67.
PHP
<?php
// A O(n) time and O(1) extra
// space PHP solution to calculate
// the Permutation Coefficient
function PermutationCoeff( $n, $k)
{
$Fn = 1; $Fk;
// Compute n! and (n-k)!
for ( $i = 1; $i <= $n; $i++)
{
$Fn *= $i;
if ($i == $n - $k)
$Fk = $Fn;
}
$coeff = $Fn / $Fk;
return $coeff;
}
// Driver Code
$n = 10; $k = 2;
echo "Value of P(" , $n , ", " , $k , ")
is " , PermutationCoeff($n, $k);
// This code is contributed by anuj_67.
?>
2397
Chapter 332. Permutation Coefficient
Output :
Value of P(10, 2) is 90
Source
https://www.geeksforgeeks.org/permutation-coefficient/
2398
Chapter 333
2399
Chapter 333. Prefix Sum of Matrix (Or 2D Array)
Example :
C++
2400
Chapter 333. Prefix Sum of Matrix (Or 2D Array)
Java
2401
Chapter 333. Prefix Sum of Matrix (Or 2D Array)
Python3
2402
Chapter 333. Prefix Sum of Matrix (Or 2D Array)
a[0][i])
for i in range(0, R) :
psa[i][0] = (psa[i - 1][0] +
a[i][0])
# updating the values in
# the cells as per the
# general formula
for i in range(1, R) :
for j in range(1, C) :
# values in the cells of
# new array are updated
psa[i][j] = (psa[i - 1][j] +
psa[i][j - 1] -
psa[i - 1][j - 1] +
a[i][j])
# displaying the values
# of the new array
for i in range(0, R) :
for j in range(0, C) :
print (psa[i][j],
end = " ")
print ()
# Driver Code
a = [[ 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1 ]]
prefixSum2D(a)
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
2403
Chapter 333. Prefix Sum of Matrix (Or 2D Array)
{
int R = a.GetLength(0);
int C = a.GetLength(1);
int [,]psa = new int[R, C];
psa[0, 0] = a[0, 0];
// Filling first row
// and first column
for (int i = 1; i < C; i++)
psa[0, i] = psa[0, i - 1] +
a[0, i];
for (int i = 1; i < R; i++)
psa[i, 0] = psa[i - 1, 0] +
a[i, 0];
// updating the values in the
// cells as per the general formula.
for (int i = 1; i < R; i++)
for (int j = 1; j < C; j++)
// values in the cells of
// new array are updated
psa[i, j] = psa[i - 1, j] +
psa[i, j - 1] -
psa[i - 1, j - 1] +
a[i, j];
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
Console.Write(psa[i, j] + " ");
Console.WriteLine();
}
}
// Driver Code
static void Main()
{
int [,]a = new int[,]{{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1}};
prefixSum2D(a);
}
}
2404
Chapter 333. Prefix Sum of Matrix (Or 2D Array)
PHP
<?php
// PHP Program to find
// prefix sum of 2d array
$R = 4;
$C = 5;
// calculating new array
function prefixSum2D($a)
{
global $C, $R;
$psa = array();
$psa[0][0] = $a[0][0];
// Filling first row
// and first column
for ($i = 1; $i < $C; $i++)
$psa[0][$i] = $psa[0][$i - 1] +
$a[0][$i];
for ($i = 0; $i < $R; $i++)
$psa[$i][0] = $psa[$i - 1][0] +
$a[$i][0];
// updating the values in
// the cells as per the
// general formula
for ($i = 1; $i < $R; $i++)
{
for ($j = 1; $j < $C; $j++)
// values in the cells of
// new array are updated
$psa[$i][$j] = $psa[$i - 1][$j] +
$psa[$i][$j - 1] -
$psa[$i - 1][$j - 1] +
$a[$i][$j];
}
// displaying the values
// of the new array
for ($i = 0; $i < $R; $i++)
{
for ($j = 0; $j < $C; $j++)
echo ($psa[$i][$j]. " ");
echo ("\n");
2405
Chapter 333. Prefix Sum of Matrix (Or 2D Array)
}
}
// Driver Code
$a = array(array( 1, 1, 1, 1, 1 ),
array( 1, 1, 1, 1, 1 ),
array( 1, 1, 1, 1, 1 ),
array( 1, 1, 1, 1, 1 ));
prefixSum2D($a);
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output :
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
Source
https://www.geeksforgeeks.org/prefix-sum-2d-array/
2406
Chapter 334
Input : n = 5
Output : 3 2 1 1 0
Input : n = 8
Output : 13 8 5 3 2 1 1 0
Algorithm
C++
2407
Chapter 334. Print Fibonacci Series in reverse order
{
int a[n];
// assigning first and second elements
a[0] = 0;
a[1] = 1;
for (int i = 2; i < n; i++) {
// storing sum in the
// preceding location
a[i] = a[i - 2] + a[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
// printing array in
// reverse order
cout << a[i] << " ";
}
}
// Driver function
int main()
{
int n = 5;
reverseFibonacci(n);
return 0;
}
Java
2408
Chapter 334. Print Fibonacci Series in reverse order
// storing sum in the
// preceding location
a[i] = a[i - 2] + a[i - 1];
}
for (int i = n - 1; i >= 0; i--)
{
// printing array in
// reverse order
System.out.print(a[i] +" ");
}
}
// Driver function
public static void main(String[] args)
{
int n = 5;
reverseFibonacci(n);
}
}
// This code is contributed by vt_m.
Python3
2409
Chapter 334. Print Fibonacci Series in reverse order
C#
2410
Chapter 334. Print Fibonacci Series in reverse order
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to print Fibonacci
// series in reverse order
function reverseFibonacci($n)
{
// assigning first and
// second elements
$a[0] = 0;
$a[1] = 1;
for ($i = 2; $i < $n; $i++)
{
// storing sum in the
// preceding location
$a[$i] = $a[$i - 2] +
$a[$i - 1];
}
for ($i = $n - 1; $i >= 0; $i--)
{
// printing array in
// reverse order
echo($a[$i] . " ");
}
}
// Driver COde
$n = 5;
reverseFibonacci($n);
// This code is contributed by Ajit.
?>
Output:
2411
Chapter 334. Print Fibonacci Series in reverse order
3 2 1 1 0
Improved By : jit_t
Source
https://www.geeksforgeeks.org/print-fibonacci-series-reverse-order/
2412
Chapter 335
C++
2413
Chapter 335. Print Fibonacci sequence using 2 variables
int main()
{
fib(9);
return 0;
}
Java
Python3
2414
Chapter 335. Print Fibonacci sequence using 2 variables
C#
PHP
2415
Chapter 335. Print Fibonacci sequence using 2 variables
<?php
// Simple php Program to print
// Fibonacci sequence
function fib( $n)
{
$a = 0; $b = 1; $c;
if ($n >= 0)
echo $a , " ";
if ($n >= 1)
echo $b , " ";
for ( $i = 2; $i <= $n; $i++)
{
$c = $a + $b;
echo $c , " ";
$a = $b;
$b = $c;
}
}
// Driver code
fib(9);
// This code is contributed by anuj_67.
?>
Output:
0 1 1 2 3 5 8 13 21 34
2416
Chapter 335. Print Fibonacci sequence using 2 variables
if (n >= 0)
cout << a << " ";
if (n >= 1)
cout << b << " ";
for (int i = 2; i <= n; i++) {
cout << a + b << " ";
b = a + b;
a = b - a;
}
}
// Driver code
int main()
{
fib(9);
return 0;
}
Java
2417
Chapter 335. Print Fibonacci sequence using 2 variables
Python3
C#
2418
Chapter 335. Print Fibonacci sequence using 2 variables
}
}
// Driver code
public static void Main ()
{
fib(9);
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP Program to print Fibonacci sequence
// using 2 variables
function fib( $n)
{
$a = 0; $b = 1;
if ($n >= 0)
echo $a , " ";
if ($n >= 1)
echo $b , " ";
for ($i = 2; $i <= $n; $i++)
{
echo $a + $b , " ";
$b = $a + $b;
$a = $b - $a;
}
}
// Driver code
fib(9);
// This code is contributed by anuj_67
?>
Output :
0 1 1 2 3 5 8 13 21 34
2419
Chapter 335. Print Fibonacci sequence using 2 variables
Source
https://www.geeksforgeeks.org/print-fibonacci-sequence-using-2-variables/
2420
Chapter 336
Input : BBABCBCAB
Output : BABCBAB
The above output is the longest
palindromic subsequence of given
sequence. "BBBBB" and "BBCBB" are
also palindromic subsequences of
the given sequence, but not the
longest ones.
Input : GEEKSFORGEEKS
Output : Output can be either EEKEE
or EESEE or EEGEE, ..
We have discussed a solution in below post to find length of longest palindromic subsequence.
Dynamic Programming | Set 12 (Longest Palindromic Subsequence)
In this post a solution to print the longest palindromic subsequence is discussed.
This problem is close to the Longest Common Subsequence (LCS) problem. In fact, we can
use LCS as a subroutine to solve this problem. Following is the two step solution that uses
LCS.
1) Reverse the given sequence and store the reverse in another array say rev[0..n-1]
2) LCS of the given sequence and rev[] will be the longest palindromic sequence.
3) Once we have found LCS, we can print the LCS.
2421
Chapter 336. Print Longest Palindromic Subsequence
2422
Chapter 336. Print Longest Palindromic Subsequence
lcs[index-1] = X[i-1];
i--;
j--;
// reduce values of i, j and index
index--;
}
// If not same, then find the larger of
// two and go in the direction of larger
// value
else if (L[i-1][j] > L[i][j-1])
i--;
else
j--;
}
return lcs;
}
// Returns longest palindromic subsequence
// of str
string longestPalSubseq(string &str)
{
// Find reverse of str
string rev = str;
reverse(rev.begin(), rev.end());
// Return LCS of str and its reverse
return lcs(str, rev);
}
/* Driver program to test above function */
int main()
{
string str = "GEEKSFORGEEKS";
cout << longestPalSubseq(str);
return 0;
}
Output:
EEGEE
Source
https://www.geeksforgeeks.org/print-longest-palindromic-subsequence/
2423
Chapter 337
Input: (5, 24), (39, 60), (15, 28), (27, 40), (50, 90)
Output: (5, 24), (27, 40), (50, 90)
In previous post, we have discussed about Maximum Length Chain of Pairs problem. How-
ever, the post only covered code related to finding the length of maximum size chain, but
not to the construction of maximum size chain. In this post, we will discuss how to construct
Maximum Length Chain of Pairs itself.
The idea is to first sort given pairs in increasing order of their first element. Let arr[0..n-1]
be the input array of pairs after sorting. We define vector L such that L[i] is itself is a vector
that stores Maximum Length Chain of Pairs of arr[0..i] that ends with arr[i]. Therefore for
an index i, L[i] can be recursively written as –
L[0] = {arr[0]}
L[i] = {Max(L[j])} + arr[i] where j < i and arr[j].b < arr[i].a
= arr[i], if there is no such j
2424
Chapter 337. Print Maximum Length Chain of Pairs
For example, for (5, 24), (39, 60), (15, 28), (27, 40), (50, 90)
Please note sorting of pairs is done as we need to find the maximum pair length and ordering
doesn’t matter here. If we don’t sort, we will get pairs in increasing order but they won’t
be maximum possible pairs.
Below is C++ implementation of above idea –
2425
Chapter 337. Print Maximum Length Chain of Pairs
{
// for every j less than i
for (int j = 0; j < i; j++)
{
// L[i] = {Max(L[j])} + arr[i]
// where j < i and arr[j].b < arr[i].a
if ((arr[j].b < arr[i].a) &&
(L[j].size() > L[i].size()))
L[i] = L[j];
}
L[i].push_back(arr[i]);
}
// print max length vector
vector<Pair> maxChain;
for (vector<Pair> x : L)
if (x.size() > maxChain.size())
maxChain = x;
for (Pair pair : maxChain)
cout << "(" << pair.a << ", "
<< pair.b << ") ";
}
// Driver Function
int main()
{
Pair a[] = {{5, 29}, {39, 40}, {15, 28},
{27, 40}, {50, 90}};
int n = sizeof(a)/sizeof(a[0]);
vector<Pair> arr(a, a + n);
maxChainLength(arr);
return 0;
}
Output:
Time complexity of above Dynamic Programming solution is O(n2 ) where n is the number
of pairs.
Auxiliary space used by the program is O(n2 ).
2426
Chapter 337. Print Maximum Length Chain of Pairs
Source
https://www.geeksforgeeks.org/print-maximum-length-chain-of-pairs/
2427
Chapter 338
2428
Chapter 338. Print all distinct characters of a string in order (3 Methods)
C++
Java
2429
Chapter 338. Print all distinct characters of a string in order (3 Methods)
{
// Create an array of size 256 and count of
// every character in it
int[] count = new int[NO_OF_CHARS];
/* Count array with frequency of characters */
int i;
for (i = 0; i < str.length(); i++)
if(str.charAt(i)!=' ')
count[(int)str.charAt(i)]++;
int n = i;
// Print characters having count more than 0
for (i = 0; i < n; i++)
if (count[(int)str.charAt(i)] == 1)
System.out.print(str.charAt(i));
}
/* Driver program*/
public static void main(String args[])
{
String str = "GeeksforGeeks";
printDistinct(str);
}
}
// This code is contributed by Sumit Ghosh
C#
2430
Chapter 338. Print all distinct characters of a string in order (3 Methods)
int i;
for (i = 0; i < str.Length; i++)
if(str[i]!=' ')
count[(int)str[i]]++;
int n = i;
// Print characters having count
// more than 0
for (i = 0; i < n; i++)
if (count[(int)str[i]] == 1)
Console.Write(str[i]);
}
/* Driver program*/
public static void Main()
{
String str = "GeeksforGeeks";
printDistinct(str);
}
}
// This code is contributed by parashar.
Output:
for
1. Initialize all values in count[] as 0 and all values in index[] as n where n is length of
string.
2. Traverse the input string str and do following for every character c = str[i].
• Increment count[x].
• If count[x] is 1, then store index of x in index[x], i.e., index[x] = i
• If count[x] is 2, then remove x from index[], i.e., index[x] = n
3. Now index[] has indexes of all distinct characters. Sort indexes and print characters
using it. Note that this step takes O(1) time assuming number of characters are fixed
(typically 256)
2431
Chapter 338. Print all distinct characters of a string in order (3 Methods)
C++
2432
Chapter 338. Print all distinct characters of a string in order (3 Methods)
index[x] = i;
// If character repeats, then remove it from
// index[]
if (count[x] == 2)
index[x] = n;
}
// Since size of index is constant, below operations
// take constant time.
sort(index, index+MAX_CHAR);
for (int i=0; i<MAX_CHAR && index[i] != n; i++)
cout << str[index[i]];
}
// Driver code
int main()
{
string str = "GeeksforGeeks";
printDistinct(str);
return 0;
}
Java
2433
Chapter 338. Print all distinct characters of a string in order (3 Methods)
2434
Chapter 338. Print all distinct characters of a string in order (3 Methods)
C#
2435
Chapter 338. Print all distinct characters of a string in order (3 Methods)
// If this is first occurrence, then
// set value in index as index of it.
if (count[x] == 1 && x !=' ')
index[x] = i;
// If character repeats, then remove
// it from index[]
if (count[x] == 2)
index[x] = n;
}
// Since size of index is constant, below
// operations take constant time.
Array.Sort(index);
for (int i = 0; i < MAX_CHAR &&
index[i] != n; i++)
Console.Write(str[index[i]]);
}
// Driver code
public static void Main()
{
string str = "GeeksforGeeks";
printDistinct(str);
}
}
// This code is contributed by nitin mittal.
Output:
for
Source
https://www.geeksforgeeks.org/print-all-distinct-characters-of-a-string-in-order-3-methods/
2436
Chapter 339
This problem is an extension of longest common subsequence. We first find length of LCS
and store all LCS in 2D table using Memoization (or Dynamic Programming). Then we
search all characters from ‘a’ to ‘z’ (to output sorted order) in both strings. If a character is
found in both strings and current positions of character lead to LCS, we recursively search
all occurrences with current LCS length plus 1.
Below is the implementation of algorithm.
2437
Chapter 339. Print all longest common sub-sequences in lexicographical order
2438
Chapter 339. Print all longest common sub-sequences in lexicographical order
}
// if we are done with all the characters of both string
if (indx1==len1 || indx2==len2)
return;
// here we have to print all sub-sequences lexicographically,
// that's why we start from 'a'to'z' if this character is
// present in both of them then append it in data[] and same
// remaining part
for (char ch='a'; ch<='z'; ch++)
{
// done is a flag to tell that we have printed all the
// subsequences corresponding to current character
bool done = false;
for (int i=indx1; i<len1; i++)
{
// if character ch is present in str1 then check if
// it is present in str2
if (ch==str1[i])
{
for (int j=indx2; j<len2; j++)
{
// if ch is present in both of them and
// remaining length is equal to remaining
// lcs length then add ch in sub-sequenece
if (ch==str2[j] &&
lcs(str1, str2, len1, len2, i, j) == lcslen-currlcs)
{
data[currlcs] = ch;
printAll(str1, str2, len1, len2, data, i+1, j+1, currlcs+1);
done = true;
break;
}
}
}
// If we found LCS beginning with current character.
if (done)
break;
}
}
}
// This function prints all LCS of str1 and str2
// in lexicographic order.
void prinlAllLCSSorted(string str1, string str2)
2439
Chapter 339. Print all longest common sub-sequences in lexicographical order
{
// Find lengths of both strings
int len1 = str1.length(), len2 = str2.length();
// Find length of LCS
memset(dp, -1, sizeof(dp));
lcslen = lcs(str1, str2, len1, len2, 0, 0);
// Print all LCS using recursive backtracking
// data[] is used to store individual LCS.
char data[MAX];
printAll(str1, str2, len1, len2, data, 0, 0, 0);
}
// Driver program to run the case
int main()
{
string str1 = "abcabcaa", str2 = "acbacba";
prinlAllLCSSorted(str1, str2);
return 0;
}
Output:
ababa
abaca
abcba
acaba
acaca
acbaa
acbca
Source
https://www.geeksforgeeks.org/print-longest-common-sub-sequences-lexicographical-order/
2440
Chapter 340
Print all possible ways to convert one string into another string | Edit-Distance - Geeks-
forGeeks
Prerequisite: Dynamic Programming | Set 5 (Edit Distance)
Given two strings str1 and str2, the task is to print the all possible ways to convert ‘str1’
into ‘str2’.
Below are the operations that can be performed on “str1”:
1. Insert
2. Remove
3. Replace
All of the above operations are of equal cost. The task is to print all the various ways to
convert ‘str1’ into ‘str2’ using the minimum number of edits (operations) required, where a
“way” comprises of the series of all such operations required.
Examples:
2441
Chapter 340. Print all possible ways to convert one string into another string |
Edit-Distance
Add d
Change e to f
Change b to x
Method 3:
Change f to h
Change e to d
Add f
Change b to x
Note that since the DP matrix contains one extra row and coloumn at 0 indices, String
indexes will be decreased by one. i.e. DP[i][j] corresponds to i-1 index of str1 and j-1 index
of str2.
Now, if the characters were not equal, that means this matrix element DP[i][j] was obtained
from the minimum of DP[i-1][j-1], DP[i][j-1] and DP[i-1][j], plus 1. Hence, check from where
this element was from.
1. If DP[i][j] == DP[i-1][j-1] + 1
It means the character was replaced from str1[i] to str2[j]. Proceed diagonally.
2. If DP[i][j] == DP[i][j-1] + 1
It means the character was Added from str2[j]. Proceed left.
3. If DP[i][j] == DP[i-1][j] + 1
It means the character str1[i] was deleted. Proceed up.
Once the end i.e., (i==0 or j==0 ) of either string is reached, converting of one string to
other is done. We will have printed all the set of operations required.
Below is the implementation of the above approach:
2442
Chapter 340. Print all possible ways to convert one string into another string |
Edit-Distance
{
int i = s1.length();
int j = s2.length();
// check till the end
while (i != 0 && j != 0) {
// if characters are same
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
i--;
j--;
}
// Replace
else if (dp[i][j] == dp[i - 1][j - 1] + 1) {
System.out.println("change " + s1.charAt(i - 1) + " to " + s2.charAt(j - 1));
i--;
j--;
}
// Delete the character
else if (dp[i][j] == dp[i - 1][j] + 1) {
System.out.println("Delete " + s1.charAt(i - 1));
i--;
}
// Add the character
else if (dp[i][j] == dp[i][j - 1] + 1) {
System.out.println("Add " + s2.charAt(j - 1));
j--;
}
}
}
// Function to compute the DP matrix
static void editDP(String s1, String s2)
{
int l1 = s1.length();
int l2 = s2.length();
int[][] DP = new int[l1 + 1][l2 + 1];
// initilize by the maximum edits possible
for (int i = 0; i <= l1; i++)
DP[i][0] = i;
for (int j = 0; j <= l2; j++)
DP[0][j] = j;
// Compute the DP matrix
2443
Chapter 340. Print all possible ways to convert one string into another string |
Edit-Distance
Output:
change f to h
change e to d
Add f
2444
Chapter 340. Print all possible ways to convert one string into another string |
Edit-Distance
change b to x
2445
Chapter 340. Print all possible ways to convert one string into another string |
Edit-Distance
2446
Chapter 340. Print all possible ways to convert one string into another string |
Edit-Distance
2447
Chapter 340. Print all possible ways to convert one string into another string |
Edit-Distance
2448
Chapter 340. Print all possible ways to convert one string into another string |
Edit-Distance
Output:
Method 1 :
Add h
Change f to d
Change e to f
Change b to x
Method 2 :
Change f to h
Add d
Change e to f
Change b to x
Method 3 :
Change f to h
Change e to d
Add f
Change b to x
Source
https://www.geeksforgeeks.org/print-all-possible-ways-to-convert-one-string-into-another-string-edit-distance/
2449
Chapter 341
1. Check if dp[i-1][sum] is true or not. If it is true, then current element does not
contribute to sum k. Add this element to set 2. Update index i by i-1 and sum
remains unchanged.
2450
Chapter 341. Print equal sum sets of array (Partition Problem) | Set 2
2. If dp[i-1][sum] is false, then current element contribute to sum k. Add current element
to set 1. Update index i by i-1 and sum by sum-arr[i-1].
C++
2451
Chapter 341. Print equal sum sets of array (Partition Problem) | Set 2
2452
Chapter 341. Print equal sum sets of array (Partition Problem) | Set 2
}
// Print elements of both the sets.
cout << "Set 1 elements: ";
for (i = 0; i < set1.size(); i++)
cout << set1[i] << " ";
cout << "\nSet 2 elements: ";
for (i = 0; i < set2.size(); i++)
cout << set2[i] << " ";
}
// Driver program.
int main()
{
int arr[] = { 5, 5, 1, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
printEqualSumSets(arr, n);
return 0;
}
Java
2453
Chapter 341. Print equal sum sets of array (Partition Problem) | Set 2
}
// Divide sum by 2 to find
// sum of two possible subsets.
int k = sum >> 1;
// Boolean DP table to store
// result of states.
// dp[i,j] = true if there is a
// subset of elements in first i
// elements of array that has sum
// equal to j.
boolean [][]dp = new boolean[n + 1][k + 1];
// If number of elements are zero,
// then no sum can be obtained.
for (i = 1; i <= k; i++)
dp[0][i] = false;
// Sum 0 can be obtained by
// not selecting any element.
for (i = 0; i <= n; i++)
dp[i][0] = true;
// Fill the DP table
// in bottom up manner.
for (i = 1; i <= n; i++)
{
for (currSum = 1;
currSum <= k;
currSum++)
{
// Excluding current element.
dp[i][currSum] = dp[i - 1][currSum];
// Including current element
if (arr[i - 1] <= currSum)
dp[i][currSum] = dp[i][currSum] |
dp[i - 1][currSum - arr[i - 1]];
}
}
// Required sets set1 and set2.
List<Integer> set1 = new ArrayList<Integer>();
List<Integer> set2 = new ArrayList<Integer>();
// If partition is not possible
2454
Chapter 341. Print equal sum sets of array (Partition Problem) | Set 2
2455
Chapter 341. Print equal sum sets of array (Partition Problem) | Set 2
C#
// C# program to print
// equal sum sets of array.
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
// Function to print equal
// sum sets of array.
static void printEqualSumSets(int []arr,
int n)
{
int i, currSum, sum = 0;
// Finding sum of array elements
for (i = 0; i < arr.Length; i++)
sum += arr[i];
// Check sum is even or odd.
// If odd then array cannot
// be partitioned. Print -1
// and return.
if ((sum & 1) == 1)
{
Console.Write("-1");
return;
}
// Divide sum by 2 to find
// sum of two possible subsets.
int k = sum >> 1;
// Boolean DP table to store
// result of states.
// dp[i,j] = true if there is a
// subset of elements in first i
2456
Chapter 341. Print equal sum sets of array (Partition Problem) | Set 2
2457
Chapter 341. Print equal sum sets of array (Partition Problem) | Set 2
Output :
Set 1 elements: 1 5 5
2458
Chapter 341. Print equal sum sets of array (Partition Problem) | Set 2
Set 2 elements: 11
Source
https://www.geeksforgeeks.org/print-equal-sum-sets-array-partition-problem-set-2/
2459
Chapter 342
We have already discussed a solution in Partition Problem to find if array can be partitioned
or not. In this post, we print two sets are also printed. We post pass two vectors set1 and
set2 and two sum variables sum1 and sum2. Traverse the array recursively. At every array
position there are two choices: either add current element to set 1 or to set 2. Recursively
call for both the conditions and update the vectors set1 and set2 accordingly. If current
element is added to set 1 then add current element to sum1 and insert it in vector set 1.
Repeat same if current elememt is included in set 2. At the end of array traversal compare
both the sums. If both the sums are equal then print both the vectors otherwise backtrack
to check other possibilities.
Implementation:
2460
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
C++
2461
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
set1.push_back(arr[pos]);
/// Recursive call after adding current element to set 1.
bool res = findSets(arr, n, set1, set2, sum1 + arr[pos],
sum2, pos + 1);
/// If this inclusion results in equal sum sets partition
/// then return true to show desired sets are found.
if (res)
return res;
/// If not then backtrack by removing current element
/// from set1 and include it in set 2.
set1.pop_back();
set2.push_back(arr[pos]);
/// Recursive call after including current element to set 2.
return findSets(arr, n, set1, set2, sum1, sum2 + arr[pos],
pos + 1);
}
/// Return true if array arr can be partitioned
/// into two equal sum sets or not.
bool isPartitionPoss(int arr[], int n)
{
/// Calculate sum of elements in array.
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
/// If sum is odd then array cannot be
/// partitioned.
if (sum % 2 != 0)
return false;
/// Declare vectors to store both the sets.
vector<int> set1, set2;
/// Find both the sets.
return findSets(arr, n, set1, set2, 0, 0, 0);
}
// Driver code
int main()
{
int arr[] = { 5, 5, 1, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
2462
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
Java
2463
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
if (pos == n) {
// If sums are equal print
// both sets and return true
// to show sets are found.
if (sum1 == sum2) {
printSets();
return true;
}
// If sums are not equal
// then return sets are not
// found.
else
return false;
}
// Add current element to set 1.
set1.add(arr[pos]);
// Recursive call after adding
// current element to set 1.
boolean res = findSets(arr, n, sum1 + arr[pos],
sum2, pos + 1);
// If this inclusion results in
// equal sum sets partition then
// return true to show desired
// sets are found.
if (res == true)
return res;
// If not then backtrack by removing
// current element from set1 and
// include it in set 2.
set1.remove(set1.size() - 1);
set2.add(arr[pos]);
// Recursive call after including
// current element to set 2.
return findSets(arr, n, sum1, sum2
+ arr[pos], pos + 1);
}
// Return true if array arr can be
// partitioned into two equal sum
// sets or not.
static boolean isPartitionPoss(Integer []arr,
2464
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
int n)
{
// Calculate sum of elements in
// array.
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// If sum is odd then array cannot
// be partitioned.
if (sum % 2 != 0)
return false;
/// Find both the sets.
return findSets(arr, n, 0, 0, 0);
}
// Driver code
public static void main(String args[])
{
Integer []arr = { 5, 5, 1, 11 };
int n = arr.length;
if (isPartitionPoss(arr, n) == false)
{
System.out.print("-1");
}
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
Python3
2465
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
2466
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
C#
2467
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
/// Print set 1.
for (i = 0; i < set1.Count; i++) {
Console.Write(set1[i] + " ");
}
Console.WriteLine();
/// Print set 2.
for (i = 0; i < set2.Count; i++) {
Console.Write(set2[i] + " ");
}
}
// Utility function to find the sets
// of the array which have equal sum.
static bool findSets(int []arr, int n,
ref List<int> set1,
ref List<int> set2,
int sum1, int sum2,
int pos)
{
// If entire array is traversed,
// compare both the sums.
if (pos == n) {
// If sums are equal print
// both sets and return true
// to show sets are found.
if (sum1 == sum2) {
printSets(set1, set2);
return true;
}
// If sums are not equal
// then return sets are not
// found.
else
return false;
}
// Add current element to set 1.
set1.Add(arr[pos]);
// Recursive call after adding
// current element to set 1.
bool res = findSets(arr, n, ref set1,
2468
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
2469
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
PHP
<?php
// PHP program to print equal sum
// two subsets of an array if it
// can be partitioned into subsets.
// Function to print the equal
// sum sets of the array.
function printSets($set1, $set2)
{
$i = 0;
// Print set 1.
for ($i = 0; $i < count($set1); $i++)
{
echo ($set1[$i]." ");
}
echo ("\n");
// Print set 2.
for ($i = 0; $i < count($set2); $i++)
{
echo ($set2[$i]." ");
}
}
// Utility function to find the
// sets of the array which have
2470
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
// equal sum.
function findSets($arr, $n, &$set1,
&$set2, $sum1,
$sum2, $pos)
{
// If entire array is traversed,
// compare both the sums.
if ($pos == $n)
{
// If sums are equal print
// both sets and return
// true to show sets are found.
if ($sum1 == $sum2)
{
printSets($set1, $set2);
return true;
}
// If sums are not equal then
// return sets are not found.
else
return false;
}
// Add current element to set 1.
array_push($set1, $arr[$pos]);
// Recursive call after adding
// current element to set 1.
$res = findSets($arr, $n, $set1, $set2,
$sum1 + $arr[$pos],
$sum2, $pos + 1);
// If this inclusion results in
// equal sum sets partition then
// return true to show desired
// sets are found.
if ($res)
return $res;
// If not then backtrack by
// removing current element
// from set1 and include it
// in set 2.
array_pop($set1);
array_push($set2, $arr[$pos]);
2471
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
// Recursive call after including
// current element to set 2.
return findSets($arr, $n, $set1, $set2,
$sum1, $sum2 + $arr[$pos],
$pos + 1);
}
// Return true if array arr
// can be partitioned into
// two equal sum sets or not.
function isPartitionPoss($arr, $n)
{
// Calculate sum of
// elements in array.
$sum = 0;
for ($i = 0; $i < $n; $i++)
$sum += $arr[$i];
// If sum is odd then array
// cannot be partitioned.
if ($sum % 2 != 0)
return false;
// Declare vectors to
// store both the sets.
$set1 = array();
$set2 = array();
// Find both the sets.
return findSets($arr, $n, $set1,
$set2, 0, 0, 0);
}
// Driver code
$arr= array( 5, 5, 1, 11 );
$n = count($arr);
if (isPartitionPoss($arr, $n) == false)
echo ("-1");
// This code is contributed by
// Manish Shaw (manishshaw1)
?>
Output:
2472
Chapter 342. Print equal sum sets of array (Partition problem) | Set 1
5 5 1
11
Source
https://www.geeksforgeeks.org/print-equal-sum-sets-array-partition-problem/
2473
Chapter 343
Print n terms of
Newman-Conway Sequence
Input : 13
Output : 1 1 2 2 3 4 4 4 5 6 7 7 8
Input : 20
Output : 1 1 2 2 3 4 4 4 5 6 7 7 8 8 8 8 9 10 11 12
C++
2474
Chapter 343. Print n terms of Newman-Conway Sequence
{
// Declare array to store sequence
int f[n + 1];
f[0] = 0;
f[1] = 1;
f[2] = 1;
cout << f[1] << " " << f[2] << " ";
for (int i = 3; i <= n; i++) {
f[i] = f[f[i - 1]] + f[i - f[i - 1]];
cout << f[i] << " ";
}
}
// Driver Program
int main()
{
int n = 13;
sequence(n);
return 0;
}
Java
2475
Chapter 343. Print n terms of Newman-Conway Sequence
//Driver code
public static void main(String []args)
{
int n = 13 ;
sequence(n);
}
}
// This program is contributed
// by upendra singh bartwal
Python3
C#
2476
Chapter 343. Print n terms of Newman-Conway Sequence
PHP
<?php
// PHP Program to print n terms
// of Newman-Conway Sequence
// Function to find
// the n-th element
function sequence($n)
{
// Declare array to
// store sequence
$f=array(0);
$f[0] = 0;
$f[1] = 1;
2477
Chapter 343. Print n terms of Newman-Conway Sequence
$f[2] = 1;
echo $f[1] , " " , $f[2] , " ";
for ($i = 3; $i <= $n; $i++)
{
$f[$i] = $f[$f[$i - 1]] +
$f[$i - $f[$i - 1]];
echo $f[$i], " ";
}
}
// Driver Code
{
$n = 13;
sequence($n);
return 0;
}
// This code is contributed by nitin mittal.
?>
Output :
1 1 2 2 3 4 4 4 5 6 7 7 8
Source
https://www.geeksforgeeks.org/print-n-terms-newman-conway-sequence/
2478
Chapter 344
Approach :
Let val[] = {1, 4, 5, 7}, wt[] = {1, 3, 4, 5}
W = 7.
The 2d knapsack table will look like :
2479
Chapter 344. Printing Items in 0/1 Knapsack
2480
Chapter 344. Printing Items in 0/1 Knapsack
Java
2481
Chapter 344. Printing Items in 0/1 Knapsack
2482
Chapter 344. Printing Items in 0/1 Knapsack
// This item is included.
System.out.print(wt[i - 1] + " ");
// Since this weight is included its
// value is deducted
res = res - val[i - 1];
w = w - wt[i - 1];
}
}
}
// Driver code
public static void main(String arg[])
{
int val[] = { 60, 100, 120 };
int wt[] = { 10, 20, 30 };
int W = 50;
int n = val.length;
printknapSack(W, wt, val, n);
}
}
// This code is contributed by Anant Agarwal.
Python3
2483
Chapter 344. Printing Items in 0/1 Knapsack
Output:
220
30 20
Improved By : aryan21
Source
https://www.geeksforgeeks.org/printing-items-01-knapsack/
2484
Chapter 345
In previous post, we have discussed about Longest Bitonic Subsequence problem. However,
the post only covered code related to finding maximum sum of increasing subsequence, but
not to the construction of subsequence. In this post, we will discuss how to construct Longest
Bitonic Subsequence itself.
Let arr[0..n-1] be the input array. We define vector LIS such that LIS[i] is itself is a vector
that stores Longest Increasing Subsequence of arr[0..i] that ends with arr[i]. Therefore for
an index i, LIS[i] can be recursively written as –
2485
Chapter 345. Printing Longest Bitonic Subsequence
LIS[0] = {arr[O]}
LIS[i] = {Max(LIS[j])} + arr[i] where j < i and arr[j] < arr[i]
= arr[i], if there is no such j
We also define a vector LDS such that LDS[i] is itself is a vector that stores Longest De-
creasing Subsequence of arr[i..n] that starts with arr[i]. Therefore for an index i, LDS[i] can
be recursively written as –
LDS[n] = {arr[n]}
LDS[i] = arr[i] + {Max(LDS[j])} where j > i and arr[j] < arr[i]
= arr[i], if there is no such j
LIS[0]: 1
LIS[1]: 1 11
LIS[2]: 1 2
LIS[3]: 1 2 10
LIS[4]: 1 2 4
LIS[5]: 1 2 4 5
LIS[6]: 1 2
LIS[7]: 1
LDS[0]: 1
LDS[1]: 11 10 5 2 1
LDS[2]: 2 1
LDS[3]: 10 5 2 1
LDS[4]: 4 2 1
LDS[5]: 5 2 1
LDS[6]: 2 1
LDS[7]: 1
LIS[1] + LDS[1] = [1 11 10 5 2 1] OR
LIS[3] + LDS[3] = [1 2 10 5 2 1] OR
LIS[5] + LDS[5] = [1 2 4 5 2 1]
2486
Chapter 345. Printing Longest Bitonic Subsequence
#include <bits/stdc++.h>
using namespace std;
// Utility function to print Longest Bitonic
// Subsequence
void print(vector<int>& arr, int size)
{
for(int i = 0; i < size; i++)
cout << arr[i] << " ";
}
// Function to construct and print Longest
// Bitonic Subsequence
void printLBS(int arr[], int n)
{
// LIS[i] stores the length of the longest
// increasing subsequence ending with arr[i]
vector<vector<int>> LIS(n);
// initialize LIS[0] to arr[0]
LIS[0].push_back(arr[0]);
// Compute LIS values from left to right
for (int i = 1; i < n; i++)
{
// for every j less than i
for (int j = 0; j < i; j++)
{
if ((arr[j] < arr[i]) &&
(LIS[j].size() > LIS[i].size()))
LIS[i] = LIS[j];
}
LIS[i].push_back(arr[i]);
}
/* LIS[i] now stores Maximum Increasing
Subsequence of arr[0..i] that ends with
arr[i] */
// LDS[i] stores the length of the longest
// decreasing subsequence starting with arr[i]
vector<vector<int>> LDS(n);
// initialize LDS[n-1] to arr[n-1]
LDS[n - 1].push_back(arr[n - 1]);
// Compute LDS values from right to left
for (int i = n - 2; i >= 0; i--)
2487
Chapter 345. Printing Longest Bitonic Subsequence
{
// for every j greater than i
for (int j = n - 1; j > i; j--)
{
if ((arr[j] < arr[i]) &&
(LDS[j].size() > LDS[i].size()))
LDS[i] = LDS[j];
}
LDS[i].push_back(arr[i]);
}
// reverse as vector as we're inserting at end
for (int i = 0; i < n; i++)
reverse(LDS[i].begin(), LDS[i].end());
/* LDS[i] now stores Maximum Decreasing Subsequence
of arr[i..n] that starts with arr[i] */
int max = 0;
int maxIndex = -1;
for (int i = 0; i < n; i++)
{
// Find maximum value of size of LIS[i] + size
// of LDS[i] - 1
if (LIS[i].size() + LDS[i].size() - 1 > max)
{
max = LIS[i].size() + LDS[i].size() - 1;
maxIndex = i;
}
}
// print all but last element of LIS[maxIndex] vector
print(LIS[maxIndex], LIS[maxIndex].size() - 1);
// print all elements of LDS[maxIndex] vector
print(LDS[maxIndex], LDS[maxIndex].size());
}
// Driver program
int main()
{
int arr[] = { 1, 11, 2, 10, 4, 5, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
printLBS(arr, n);
return 0;
}
2488
Chapter 345. Printing Longest Bitonic Subsequence
Output:
1 11 10 5 2 1
Source
https://www.geeksforgeeks.org/printing-longest-bitonic-subsequence/
2489
Chapter 346
Input:
string X = "AGTGATG"
string Y = "GTTAG"
Output:
GTAG
GTTG
Input:
string X = "AATCC"
string Y = "ACACG"
Output:
ACC
AAC
Input:
string X = "ABCBDAB"
string Y = "BDCABA"
Output:
BCAB
BCBA
BDAB
2490
Chapter 346. Printing Longest Common Subsequence | Set 2 (Printing All)
We have discussed Longest Common Subsequence (LCS) problem here. The function dis-
cussed there was mainly to find the length of LCS. We have also discussed how to print the
longest subsequence here. But as LCS for two strings is not unique, in this post we will
print out all the possible solutions to LCS problem.
Following is detailed algorithm to print the all LCS.
We construct L[m+1][n+1] table as discussed in the previous post and traverse the 2D array
starting from L[m][n]. For current cell L[i][j] in the matrix,
a) If the last characters of X and Y are same (i.e. X[i-1] == Y[j-1]), then the charcater must
be present in all LCS of substring X[0…i-1] and Y[0..j-1]. We simply recurse for L[i-1][j-1]
in the matrix and append current character to all LCS possible of substring X[0…i-2] and
Y[0..j-2].
b) If the last characters of X and Y are not same (i.e. X[i-1] != Y[j-1]), then LCS can be
constructed from either top side of the matrix (i.e. L[i-1][j]) or from left side of matrix (i.e.
L[i][j-1]) depending upon which value is greater. If both the values are equal(i.e. L[i-1][j]
== L[i][j-1]), then it will be constructed from both sides of matrix. So based on values at
L[i-1][j] and L[i][j-1], we go in direction of greater value or go in both directions if the values
are equal.
Below is recursive C++ implementation of above idea –
2491
Chapter 346. Printing Longest Common Subsequence | Set 2 (Printing All)
2492
Chapter 346. Printing Longest Common Subsequence | Set 2 (Printing All)
return L[m][n];
}
/* Driver program to test above function */
int main()
{
string X = "AGTGATG";
string Y = "GTTAG";
int m = X.length();
int n = Y.length();
cout << "LCS length is " << LCS(X, Y, m, n) << endl;
set<string> s = findLCS(X, Y, m, n);
for (string str : s)
cout << str << endl;
return 0;
}
Output:
GTAG
GTTG
Source
https://www.geeksforgeeks.org/printing-longest-common-subsequence-set-2-printing/
2493
Chapter 347
Input: [10, 5, 4, 3]
Output: [10]
Input: [3, 2, 6, 4, 5, 1]
Output: [3, 4, 5]
In previous post, we have discussed about Maximum Sum Increasing Subsequence problem.
However, the post only covered code related to finding maximum sum of increasing subse-
quence, but not to the construction of subsequence. In this post, we will discuss how to
construct Maximum Sum Increasing Subsequence itself.
Let arr[0..n-1] be the input array. We define vector L such that L[i] is itself is a vector that
stores Maximum Sum Increasing Subsequence of arr[0..i] that ends with arr[i]. Therefore
for an index i, L[i] can be recursively written as
2494
Chapter 347. Printing Maximum Sum Increasing Subsequence
L[0] = {arr[0]}
L[i] = {MaxSum(L[j])} + arr[i] where j < i and arr[j] < arr[i]
= arr[i], if there is no j such that arr[j] < arr[i]
L[0]: 3
L[1]: 2
L[2]: 3 6
L[3]: 3 4
L[4]: 3 4 5
L[5]: 1
2495
Chapter 347. Printing Maximum Sum Increasing Subsequence
Output:
3 4 5
2496
Chapter 347. Printing Maximum Sum Increasing Subsequence
Source
https://www.geeksforgeeks.org/printing-maximum-sum-increasing-subsequence/
2497
Chapter 348
We have discussed how to print length of shortest possible supersequence for two given
strings here. In this post, we print the shortest supersequence.
We have already discussed below algorithm to find length of shortest supersequence in
previous post-
if (m == 0) return n;
if (n == 0) return m;
2498
Chapter 348. Printing Shortest Common Supersequence
The following table shows steps followed by the above algorithm if we solve it in bottom-up
manner using Dynamic Programming for strings X = “AGGTAB” and Y = “GXTX-
AYB”,
Using the DP solution matrix, we can easily print shortest supersequence of two strings by
following below steps –
2499
Chapter 348. Printing Shortest Common Supersequence
2500
Chapter 348. Printing Shortest Common Supersequence
dp[i][j] = i;
else if(X[i - 1] == Y[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]);
}
}
// Following code is used to print shortest supersequence
// dp[m][n] stores the length of the shortest supersequence
// of X and Y
int index = dp[m][n];
// string to store the shortest supersequence
string str;
// Start from the bottom right corner and one by one
// push characters in output string
int i = m, j = n;
while (i > 0 && j > 0)
{
// If current character in X and Y are same, then
// current character is part of shortest supersequence
if (X[i - 1] == Y[j - 1])
{
// Put current character in result
str.push_back(X[i - 1]);
// reduce values of i, j and index
i--, j--, index--;
}
// If current character in X and Y are different
else if (dp[i - 1][j] > dp[i][j - 1])
{
// Put current character of Y in result
str.push_back(Y[j - 1]);
// reduce values of j and index
j--, index--;
}
else
{
// Put current character of X in result
str.push_back(X[i - 1]);
// reduce values of i and index
2501
Chapter 348. Printing Shortest Common Supersequence
i--, index--;
}
}
// If Y reaches its end, put remaining characters
// of X in the result string
while (i > 0)
{
str.push_back(X[i - 1]);
i--, index--;
}
// If X reaches its end, put remaining characters
// of Y in the result string
while (j > 0)
{
str.push_back(Y[j - 1]);
j--, index--;
}
// reverse the string and return it
reverse(str.begin(), str.end());
return str;
}
// Driver program to test above function
int main()
{
string X = "AGGTAB";
string Y = "GXTXAYB";
cstr << printShortestSuperSeq(X, Y);
return 0;
}
Output:
AGXGTXAYB
Source
https://www.geeksforgeeks.org/print-shortest-common-supersequence/
2502
Chapter 349
However, the order in which we parenthesize the product affects the number of simple arith-
metic operations needed to compute the product, or the efficiency. For example, suppose A
is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then,
2503
Chapter 349. Printing brackets in Matrix Chain Multiplication Problem
This problem is mainly an extension of previous post. In the previous post, we have discussed
algorithm for finding optimal cost only. Here we need print parenthssization also.
The idea is to store optimal break point for every subexpression (i, j) in a 2D array
bracket[n][n]. Once we have bracket array us constructed, we can print parenthesization
using below code.
print "(";
2504
Chapter 349. Printing brackets in Matrix Chain Multiplication Problem
print ")";
}
// C++ program to print optimal parenthesization
// in matrix chain multiplication.
#include<bits/stdc++.h>
using namespace std;
// Function for printing the optimal
// parenthesization of a matrix chain product
void printParenthesis(int i, int j, int n,
int *bracket, char &name)
{
// If only one matrix left in current segment
if (i == j)
{
cout << name++;
return;
}
cout << "(";
// Recursively put brackets around subexpression
// from i to bracket[i][j].
// Note that "*((bracket+i*n)+j)" is similar to
// bracket[i][j]
printParenthesis(i, *((bracket+i*n)+j), n,
bracket, name);
// Recursively put brackets around subexpression
// from bracket[i][j] + 1 to j.
printParenthesis(*((bracket+i*n)+j) + 1, j,
n, bracket, name);
cout << ")";
}
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
// Please refer below article for details of this
// function
// https://goo.gl/k6EYKj
void matrixChainOrder(int p[], int n)
{
/* For simplicity of the program, one extra
row and one extra column are allocated in
m[][]. 0th row and 0th column of m[][]
2505
Chapter 349. Printing brackets in Matrix Chain Multiplication Problem
2506
Chapter 349. Printing brackets in Matrix Chain Multiplication Problem
// Driver code
int main()
{
int arr[] = {40, 20, 30, 10, 30};
int n = sizeof(arr)/sizeof(arr[0]);
matrixChainOrder(arr, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/printing-brackets-matrix-chain-multiplication-problem/
2507
Chapter 350
2508
Chapter 350. Printing longest Increasing consecutive subsequence
2509
Chapter 350. Printing longest Increasing consecutive subsequence
Output:
3 4 5 6 7 8
Source
https://www.geeksforgeeks.org/printing-longest-increasing-consecutive-subsequence/
2510
Chapter 351
Let's take:
8x8 chessboard,
initial position of the knight : (0, 0),
number of steps : 1
At each step, the Knight has 8 different positions to choose from.
If it starts from (0, 0), after taking one step it will lie inside the
board only at 2 out of 8 positions, and will lie outside at other positions.
So, the probability is 2/8 = 0.25
One thing that we can observe is that at every step the Knight has 8 choices to choose from.
Suppose, the Knight has to take k steps and after taking the Kth step the knight reaches
(x,y). There are 8 different positions from where the Knight can reach to (x,y) in one step,
and they are: (x+1,y+2), (x+2,y+1), (x+2,y-1), (x+1,y-2), (x-1,y-2), (x-2,y-1), (x-2,y+1),
(x-1,y+2).
What if we already knew the probabilities of reaching these 8 positions after K-1 steps? Then,
the final probability after K steps will simply be equal to the (Σ probability of reaching each
of these 8 positions after K-1 steps)/8;
Here we are dividing by 8 because each of these 8 positions have 8 choices and position (x,y)
is one of the choice.
2511
Chapter 351. Probability of Knight to remain in the chessboard
For the positions that lie outside the board, we will either take their probabilities as 0 or
simply neglect it.
Since, we need to keep track of the probabilities at each position for every number of steps,
we need Dynamic Programming to solve this problem.
We are going to take an array dp[x][y][steps] which will store the probability of reaching
(x,y) after (steps) number of moves.
Base case : if number of steps is 0, then the probability that the Knight will remain inside
the board is 1.
Here is the implementation :
C++
2512
Chapter 351. Probability of Knight to remain in the chessboard
{
// for every position (x,y) after
// s number of steps
for (int x = 0; x < N; ++x)
{
for (int y = 0; y < N; ++y)
{
double prob = 0.0;
// for every position reachable from (x,y)
for (int i = 0; i < 8; ++i)
{
int nx = x + dx[i];
int ny = y + dy[i];
// if this position lie inside the board
if (inside(nx, ny))
prob += dp1[nx][ny][s-1] / 8.0;
}
// store the result
dp1[x][y][s] = prob;
}
}
}
// return the result
return dp1[start_x][start_y][steps];
}
// Driver program
int main()
{
// number of steps
int K = 3;
cout << findProb(0, 0, K) << endl;
return 0;
}
Java
2513
Chapter 351. Probability of Knight to remain in the chessboard
// size of the chessboard
static final int N = 8;
// direction vector for the Knight
static int dx[] = { 1, 2, 2, 1,
-1, -2, -2, -1 };
static int dy[] = { 2, 1, -1, -2,
-2, -1, 1, 2 };
// returns true if the knight is
// inside the chessboard
static boolean inside(int x, int y)
{
return (x >= 0 && x < N &&
y >= 0 && y < N);
}
// Bottom up approach for finding
// the probability to go out of
// chessboard.
static double findProb(int start_x,
int start_y, int steps)
{
// dp array
double dp1[][][] = new double[N][N][N];
// for 0 number of steps, each position
// will have probability 1
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
dp1[i][j][0] = 1;
// for every number of steps s
for (int s = 1; s <= steps; ++s) {
// for every position (x, y) after
// s number of steps
for (int x = 0; x < N; ++x) {
for (int y = 0; y < N; ++y) {
double prob = 0.0;
// for every position reachable
// from (x, y)
2514
Chapter 351. Probability of Knight to remain in the chessboard
Python3
2515
Chapter 351. Probability of Knight to remain in the chessboard
2516
Chapter 351. Probability of Knight to remain in the chessboard
# number of steps
K = 3
print(findProb(0, 0, K))
# This code is contributed by Anant Agarwal.
C#
2517
Chapter 351. Probability of Knight to remain in the chessboard
2518
Chapter 351. Probability of Knight to remain in the chessboard
Output:
0.125
Time Complexity: O(NxNxKx8) which is O(NxNxK), where N is the size of the board
and K is the number of steps.
Space Complexity: O(NxNxK)
Improved By : Sam007
Source
https://www.geeksforgeeks.org/probability-knight-remain-chessboard/
2519
Chapter 352
2520
Chapter 352. Probability of getting at least K heads in N tosses of Coins
Method 1 (Naive)
A Naive approach is to store the value of factorial in dp[] array and call it directly whenever
it is required. But the problem of this approach is that we can only able to store it up to
certain value, after that it will lead to overflow.
Below is the implementation of above approach
C++
2521
Chapter 352. Probability of getting at least K heads in N tosses of Coins
for (int i = 2; i < 20; ++i)
fact[i] = fact[i - 1] * i;
}
// Drive code
int main()
{
precompute();
// Probability of getting 2 head out of 3 coins
cout << probability(2, 3) << "\n";
// Probability of getting 3 head out of 6 coins
cout << probability(3, 6) <<"\n";
// Probability of getting 12 head out of 18 coins
cout << probability(12, 18);
return 0;
}
Java
2522
Chapter 352. Probability of getting at least K heads in N tosses of Coins
C#
2523
Chapter 352. Probability of getting at least K heads in N tosses of Coins
Output:
0.5
0.65625
0.118942
2524
Chapter 352. Probability of getting at least K heads in N tosses of Coins
Now whenever we need to find the factorial of any number, we can use
this precomputed value. For example:
Suppose if we want to find the value of nCi which can be written as:
=> nCi = n! / (i! * (n-i)! )
We will subtract this n from above result to get the final answer:
=> Pi (log2 (nCi)) = dp[n] - dp[i] - dp[n-i] - n
Tada! Now the questions boils down the summation of Pi for all i in
[k, n] will yield the answer which can be calculated easily without
overflow.
2525
Chapter 352. Probability of getting at least K heads in N tosses of Coins
Output:
0.5
2526
Chapter 352. Probability of getting at least K heads in N tosses of Coins
0.65625
0.512613
Source
https://www.geeksforgeeks.org/probability-getting-least-k-heads-n-tosses-coins/
2527
Chapter 353
Input : N = 5, P = 0.20
Output : 0.32
Explanation :-
There are two ways to reach 5.
2+3 with probability = 0.2 * 0.8 = 0.16
3+2 with probability = 0.8 * 0.2 = 0.16
So, total probability = 0.32.
C++
2528
Chapter 353. Probability of reaching a point with 2 or 3 steps at a time
Java
2529
Chapter 353. Probability of reaching a point with 2 or 3 steps at a time
Python3
C#
2530
Chapter 353. Probability of reaching a point with 2 or 3 steps at a time
class GFG {
// Returns probability to reach N
static float find_prob(int N, float P)
{
double []dp = new double[N + 1];
dp[0] = 1;
dp[1] = 0;
dp[2] = P;
dp[3] = 1 - P;
for (int i = 4; i <= N; ++i)
dp[i] = (P) * dp[i - 2] +
(1 - P) * dp[i - 3];
return ((float)(dp[N]));
}
// Driver code
public static void Main()
{
int n = 5;
float p = 0.2f;
Console.WriteLine(find_prob(n, p));
}
}
/* This code is contributed by vt_m.*/
PHP
<?php
// PHP Program to find probability to
// reach N with P probability to take
// 2 steps (1-P) to take 3 steps
// Returns probability to reach N
function find_prob($N, $P)
{
$dp;
$dp[0] = 1;
$dp[1] = 0;
$dp[2] = $P;
$dp[3] = 1 - $P;
for ($i = 4; $i <= $N; ++$i)
$dp[$i] = ($P) * $dp[$i - 2] +
(1 - $P) * $dp[$i - 3];
2531
Chapter 353. Probability of reaching a point with 2 or 3 steps at a time
return $dp[$N];
}
// Driver code
$n = 5;
$p = 0.2;
echo find_prob($n, $p);
// This code is contributed by mits.
?>
Output :
0.32
Source
https://www.geeksforgeeks.org/probability-reaching-point-2-3-steps-time/
2532
Chapter 354
The approach is to use Dynamic programming. Before getting dive into dynamic program-
minc let’s see the following observation that will be required in solving the problem.
2533
Chapter 354. Program for Bridge and Torch problem
1. When any two people cross the bridge, then the fastest person crossing time will not
be contributed in answer as both of them move with slowest person speed.
2. When some of the people will cross the river and reached the right side then only the
fastest people(smallest integer) will come back to the left side.
3. Person can only be present either left side or right side of the bridge. Thus, if we
maintain the left mask, then right mask can easily be calculated by setting the bits
‘1’ which is not present in the left mask. For instance, Right_mask = ((2n ) – 1) XOR
(left_mask).
4. Any person can easily be represented by bitmask(usually called as ‘mask’). When
ith bit of ‘mask’ is set, that means that person is present at left side of the bridge
otherwise it would be present at right side of bridge. For instance, let the mask of 6
people is 100101, which reprsents the person 1, 4, 6 are present at left side of bridge
and the person 2, 3 and 5 are present at the right side of the bridge.
2534
Chapter 354. Program for Bridge and Torch problem
2535
Chapter 354. Program for Bridge and Torch problem
Output
2536
Chapter 354. Program for Bridge and Torch problem
60
Time complexity:
Auxiliary space:
Source
https://www.geeksforgeeks.org/program-bridge-torch-problem/
2537
Chapter 355
Fn = Fn-1 + Fn-2
F0 = 0 and F1 = 1.
2538
Chapter 355. Program for Fibonacci numbers
Input : n = 2
Output : 1
Input : n = 9
Output : 34
Write a function int fib(int n) that returns Fn . For example, if n = 0, then fib() should
return 0. If n = 1, then it should return 1. For n > 1, it should return Fn-1 + Fn-2
For n = 9
Output:34
Java
2539
Chapter 355. Program for Fibonacci numbers
return n;
return fib(n-1) + fib(n-2);
}
public static void main (String args[])
{
int n = 9;
System.out.println(fib(n));
}
}
/* This code is contributed by Rajat Mishra */
Python
C#
2540
Chapter 355. Program for Fibonacci numbers
}
else
{
return Fib(n - 1) + Fib(n - 2);
}
}
// driver code
public static void Main(string[] args)
{
int n = 9;
Console.Write(Fib(n));
}
}
// This code is contributed by Sam007
PHP
<?php
// Fibonacci Series
// using Recursion
// function returns
// the Fibonacci number
function fib($n)
{
if ($n <= 1)
return $n;
return fib($n - 1) +
fib($n - 2);
}
// Driver Code
$n = 9;
echo fib($n);
// This code is contributed by aj_36
?>
Output
34
2541
Chapter 355. Program for Fibonacci numbers
fib(5)
/
fib(4) fib(3)
/ /
fib(3) fib(2) fib(2) fib(1)
/ / /
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/
fib(1) fib(0)
Extra Space: O(n) if we consider the function call stack size, otherwise O(1).
Method 2 ( Use Dynamic Programming )
We can avoid the repeated work done is the method 1 by storing the Fibonacci numbers
calculated so far.
2542
Chapter 355. Program for Fibonacci numbers
Java
Python
2543
Chapter 355. Program for Fibonacci numbers
C#
2544
Chapter 355. Program for Fibonacci numbers
}
}
// This code is contributed by anuj_67.
PHP
<?php
//Fibonacci Series using Dynamic
// Programming
function fib( $n)
{
/* Declare an array to store
Fibonacci numbers. */
// 1 extra to handle case,
// n = 0
$f = array();
$i;
/* 0th and 1st number of the
series are 0 and 1*/
$f[0] = 0;
$f[1] = 1;
for ($i = 2; $i <= $n; $i++)
{
/* Add the previous 2
numbers in the series
and store it */
$f[$i] = $f[$i-1] + $f[$i-2];
}
return $f[$n];
}
$n = 9;
echo fib($n);
// This code is contributed by
// anuj_67.
?>
Output:
2545
Chapter 355. Program for Fibonacci numbers
34
C/C++
Java
2546
Chapter 355. Program for Fibonacci numbers
{
c = a + b;
a = b;
b = c;
}
return b;
}
public static void main (String args[])
{
int n = 9;
System.out.println(fib(n));
}
}
// This code is contributed by Mihir Joshi
Python
C#
2547
Chapter 355. Program for Fibonacci numbers
PHP
<?php
// PHP program for Fibonacci Series
// using Space Optimized Method
function fib( $n)
{
$a = 0;
$b = 1;
$c;
$i;
2548
Chapter 355. Program for Fibonacci numbers
if( $n == 0)
return $a;
for($i = 2; $i <= $n; $i++)
{
$c = $a + $b;
$a = $b;
$b = $c;
}
return $b;
}
// Driver Code
$n = 9;
echo fib($n);
// This code is contributed by anuj_67.
?>
Output :
34
#include <stdio.h>
/* Helper function that multiplies 2 matrices F and M of size 2*2, and
puts the multiplication result back to F[][] */
void multiply(int F[2][2], int M[2][2]);
/* Helper function that calculates F[][] raise to the power n and puts the
result in F[][]
Note that this function is designed only for fib() and won't work as general
power function */
2549
Chapter 355. Program for Fibonacci numbers
Java
class fibonacci
{
2550
Chapter 355. Program for Fibonacci numbers
static int fib(int n)
{
int F[][] = new int[][]{{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n-1);
return F[0][0];
}
/* Helper function that multiplies 2 matrices F and M of size 2*2, and
puts the multiplication result back to F[][] */
static void multiply(int F[][], int M[][])
{
int x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
int y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
int z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
int w = F[1][0]*M[0][1] + F[1][1]*M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
/* Helper function that calculates F[][] raise to the power n and puts the
result in F[][]
Note that this function is designed only for fib() and won't work as general
power function */
static void power(int F[][], int n)
{
int i;
int M[][] = new int[][]{{1,1},{1,0}};
// n - 1 times multiply the matrix to {{1,0},{0,1}}
for (i = 2; i <= n; i++)
multiply(F, M);
}
/* Driver program to test above function */
public static void main (String args[])
{
int n = 9;
System.out.println(fib(n));
}
}
/* This code is contributed by Rajat Mishra */
2551
Chapter 355. Program for Fibonacci numbers
C#
2552
Chapter 355. Program for Fibonacci numbers
multiply(F, M);
}
/* Driver program to test above function */
public static void Main ()
{
int n = 9;
Console.WriteLine(fib(n));
}
}
// This code is contributed by anuj_67.
#include <stdio.h>
void multiply(int F[2][2], int M[2][2]);
void power(int F[2][2], int n);
/* function that returns nth Fibonacci number */
int fib(int n)
{
int F[2][2] = {{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n-1);
return F[0][0];
}
/* Optimized version of power() in method 4 */
void power(int F[2][2], int n)
{
if( n == 0 || n == 1)
return;
int M[2][2] = {{1,1},{1,0}};
2553
Chapter 355. Program for Fibonacci numbers
power(F, n/2);
multiply(F, F);
if (n%2 != 0)
multiply(F, M);
}
void multiply(int F[2][2], int M[2][2])
{
int x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
int y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
int z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
int w = F[1][0]*M[0][1] + F[1][1]*M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
/* Driver program to test above function */
int main()
{
int n = 9;
printf("%d", fib(9));
getchar();
return 0;
}
Java
2554
Chapter 355. Program for Fibonacci numbers
2555
Chapter 355. Program for Fibonacci numbers
C++
2556
Chapter 355. Program for Fibonacci numbers
int k = (n & 1)? (n+1)/2 : n/2;
// Applyting above formula [Note value n&1 is 1
// if n is odd, else 0.
f[n] = (n & 1)? (fib(k)*fib(k) + fib(k-1)*fib(k-1))
: (2*fib(k-1) + fib(k))*fib(k);
return f[n];
}
/* Driver program to test above function */
int main()
{
int n = 9;
printf("%d ", fib(n));
return 0;
}
Java
2557
Chapter 355. Program for Fibonacci numbers
Python
2558
Chapter 355. Program for Fibonacci numbers
C#
2559
Chapter 355. Program for Fibonacci numbers
// Applyting above formula
// [Note value n&1 is 1 if
// n is odd, else 0.
f[n] = (n & 1) == 1 ? (fib(k) * fib(k) +
fib(k - 1) * fib(k - 1))
: (2 * fib(k - 1) + fib(k)) *
fib(k);
return f[n];
}
// Driver Code
static void Main()
{
int n = 9;
f = new int[MAX];
Console.WriteLine(fib(n));
}
}
// This code is contributed by mits
Output :
34
Time complexity of this solution is O(Log n) as we divide the problem to half in every
recursive call.
This method is contributed by Chirag Agarwal.
Related Articles:
Large Fibonacci Numbers in Java
References:
http://en.wikipedia.org/wiki/Fibonacci_number
http://www.ics.uci.edu/~eppstein/161/960109.html
Improved By : jit_t, vt_m, humblezero, Mithun Kumar
Source
https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/
2560
Chapter 356
C++
#include<iostream>
using namespace std;
// A recursive function to find nth catalan number
unsigned long int catalan(unsigned int n)
{
2561
Chapter 356. Program for nth Catalan Number
Java
class CatalnNumber {
// A recursive function to find nth catalan number
int catalan(int n) {
int res = 0;
// Base case
if (n <= 1) {
return 1;
}
for (int i = 0; i < n; i++) {
res += catalan(i) * catalan(n - i - 1);
}
return res;
}
public static void main(String[] args) {
CatalnNumber cn = new CatalnNumber();
for (int i = 0; i < 10; i++) {
System.out.print(cn.catalan(i) + " ");
}
}
}
Python
2562
Chapter 356. Program for nth Catalan Number
C#
2563
Chapter 356. Program for nth Catalan Number
}
}
// This code is contributed by
// nitin mittal.
PHP
<?php
// PHP Program for nth
// Catalan Number
// A recursive function to
// find nth catalan number
function catalan($n)
{
// Base case
if ($n <= 1)
return 1;
// catalan(n) is sum of
// catalan(i)*catalan(n-i-1)
$res = 0;
for($i = 0; $i < $n; $i++)
$res += catalan($i) *
catalan($n - $i - 1);
return $res;
}
// Driver Code
for ($i = 0; $i < 10; $i++)
echo catalan($i), " ";
// This code is contributed aj_36
?>
Output :
The value of nth catalan number is exponential that makes the time complexity exponential.
2564
Chapter 356. Program for nth Catalan Number
#include<iostream>
using namespace std;
// A dynamic programming based function to find nth
// Catalan number
unsigned long int catalanDP(unsigned int n)
{
// Table to store results of subproblems
unsigned long int catalan[n+1];
// Initialize first two values in table
catalan[0] = catalan[1] = 1;
// Fill entries in catalan[] using recursive formula
for (int i=2; i<=n; i++)
{
catalan[i] = 0;
for (int j=0; j<i; j++)
catalan[i] += catalan[j] * catalan[i-j-1];
}
// Return last entry
return catalan[n];
}
// Driver program to test above function
int main()
{
for (int i = 0; i < 10; i++)
cout << catalanDP(i) << " ";
return 0;
}
Python
2565
Chapter 356. Program for nth Catalan Number
# Table to store results of subproblems
catalan = [0 for i in range(n + 1)]
# Initialize first two values in table
catalan[0] = 1
catalan[1] = 1
# Fill entries in catalan[] using recursive formula
for i in range(2, n + 1):
catalan[i] = 0
for j in range(i):
catalan[i] = catalan[i] + catalan[j] * catalan[i-j-1]
# Return last entry
return catalan[n]
# Driver code
for i in range (11):
print (catalanDP(i))
# This code is contributed by Aditi Sharma
PHP
<?php
// PHP program for nth Catalan Number
// A dynamic programming based function
// to find nth Catalan number
function catalanDP( $n)
{
// Table to store results
// of subproblems
$catalan= array();
// Initialize first two
// values in table
$catalan[0] = $catalan[1] = 1;
// Fill entries in catalan[]
// using recursive formula
for ($i = 2; $i <= $n; $i++)
{
$catalan[$i] = 0;
for ( $j = 0; $j < $i; $j++)
$catalan[$i] += $catalan[$j] *
$catalan[$i - $j - 1];
2566
Chapter 356. Program for nth Catalan Number
}
// Return last entry
return $catalan[$n];
}
// Driver Code
for ($i = 0; $i < 10; $i++)
echo catalanDP($i) , " ";
// This code is contributed anuj_67.
?>
Output:
C++
#include<iostream>
using namespace std;
// Returns value of Binomial Coefficient C(n, k)
unsigned long int binomialCoeff(unsigned int n, unsigned int k)
{
unsigned long int res = 1;
// Since C(n, k) = C(n, n-k)
if (k > n - k)
k = n - k;
// Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1]
for (int i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
2567
Chapter 356. Program for nth Catalan Number
return res;
}
// A Binomial coefficient based function to find nth catalan
// number in O(n) time
unsigned long int catalan(unsigned int n)
{
// Calculate value of 2nCn
unsigned long int c = binomialCoeff(2*n, n);
// return 2nCn/(n+1)
return c/(n+1);
}
// Driver program to test above functions
int main()
{
for (int i = 0; i < 10; i++)
cout << catalan(i) << " ";
return 0;
}
Python
2568
Chapter 356. Program for nth Catalan Number
print (catalan(i))
# This code is contributed by Aditi Sharma
Output:
References:
http://en.wikipedia.org/wiki/Catalan_number
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above
Improved By : icr0, jit_t, nitin mittal, vt_m
Source
https://www.geeksforgeeks.org/program-nth-catalan-number/
2569
Chapter 357
1
2 3
4 5 6
7 8 9 10
You can put water to only top glass. If you put more than 1 litre water to 1st glass, water
overflows and fills equally in both 2nd and 3rd glasses. Glass 5 will get water from both
2nd glass and 3rd glass and so on.
If you have X litre of water and you put that water in top glass, how much water will be
contained by jth glass in ith row?
Example. If you will put 2 litre on top.
1st – 1 litre
2nd – 1/2 litre
3rd – 1/2 litre
The approach is similar to Method 2 of the Pascal’s Triangle. If we take a closer look at the
problem, the problem boils down to Pascal’s Triangle.
1 ---------------- 1
2 3 ---------------- 2
4 5 6 ------------ 3
7 8 9 10 --------- 4
2570
Chapter 357. Program to find amount of water in a given glass
Each glass contributes to the two glasses down the glass. Initially, we put all water in first
glass. Then we keep 1 litre (or less than 1 litre) in it, and move rest of the water to two
glasses down to it. We follow the same process for the two glasses and all other glasses till
ith row. There will be i*(i+1)/2 glasses till ith row.
C++
2571
Chapter 357. Program to find amount of water in a given glass
Java
2572
Chapter 357. Program to find amount of water in a given glass
System.out.println("Incorrect Input");
System.exit(0);
}
// There will be i*(i+1)/2 glasses
// till ith row (including ith row)
int ll = Math.round((i * (i + 1) ));
float[] glass = new float[ll + 2];
// Put all water in first glass
int index = 0;
glass[index] = X;
// Now let the water flow to the
// downward glasses till the row
// number is less than or/ equal
// to i (given row)
// correction : X can be zero for side
// glasses as they have lower rate to fill
for (int row = 1; row <= i ; ++row)
{
// Fill glasses in a given row. Number of
// columns in a row is equal to row number
for (int col = 1;
col <= row; ++col, ++index)
{
// Get the water from current glass
X = glass[index];
// Keep the amount less than or
// equal to capacity in current glass
glass[index] = (X >= 1.0f) ? 1.0f : X;
// Get the remaining amount
X = (X >= 1.0f) ? (X - 1) : 0.0f;
// Distribute the remaining amount
// to the down two glasses
glass[index + row] += X / 2;
glass[index + row + 1] += X / 2;
}
}
// The index of jth glass in ith
// row will be i*(i-1)/2 + j - 1
return glass[(int)(i * (i - 1) /
2 + j - 1)];
}
2573
Chapter 357. Program to find amount of water in a given glass
// Driver Code
public static void main(String[] args)
{
int i = 2, j = 2;
float X = 2.0f; // Total amount of water
System.out.println("Amount of water in jth " +
"glass of ith row is: " +
findWater(i, j, X));
}
}
// This code is contributed by mits
Python3
2574
Chapter 357. Program to find amount of water in a given glass
C#
// Program to find the amount
// of water in j-th glass
// of i-th row
using System;
class GFG
2575
Chapter 357. Program to find amount of water in a given glass
{
// Returns the amount of water
// in jth glass of ith row
static float findWater(int i, int j,
float X)
{
// A row number i has maximum i
// columns. So input column
// number must be less than i
if (j > i)
{
Console.WriteLine(“Incorrect Input”);
Environment.Exit(0);
}
// There will be i*(i+1)/2 glasses
// till ith row (including ith row)
int ll = (int)Math.Round((double)(i * (i + 1)));
float[] glass = new float[ll + 2];
// Put all water in first glass
int index = 0;
glass[index] = X;
// Now let the water flow to the
// downward glasses till the row
// number is less than or/ equal
// to i (given row)
// correction : X can be zero
// for side glasses as they have
// lower rate to fill
for (int row = 1; row <= i ; ++row) { // Fill glasses in a given row. // Number of columns
in a row // is equal to row number for (int col = 1; col <= row; ++col, ++index) { // Get
the water from current glass X = glass[index]; // Keep the amount less than // or equal to
capacity in // current glass glass[index] = (X >= 1.0f) ?
1.0f : X;
// Get the remaining amount
X = (X >= 1.0f) ? (X – 1) : 0.0f;
// Distribute the remaining amount
// to the down two glasses
glass[index + row] += X / 2;
glass[index + row + 1] += X / 2;
}
}
// The index of jth glass in ith
// row will be i*(i-1)/2 + j – 1
return glass[(int)(i * (i – 1) /
2 + j – 1)];
2576
Chapter 357. Program to find amount of water in a given glass
}
// Driver Code
static void Main()
{
int i = 2, j = 2;
float X = 2.0f; // Total amount of water
Console.WriteLine(“Amount of water in jth ” +
“glass of ith row is: ” +
findWater(i, j, X));
}
}
// This code is contributed by mits
PHP
<?php
// Program to find the amount
// of water in j-th glass of
// i-th row
// Returns the amount of water
// in jth glass of ith row
function findWater($i, $j, $X)
{
// A row number i has maximum
// i columns. So input column
// number must be less than i
if ($j > $i)
{
echo "Incorrect Input\n";
return;
}
// There will be i*(i+1)/2
// glasses till ith row
// (including ith row)
// and Initialize all glasses
// as empty
$glass = array_fill(0, (int)($i *
($i + 1) / 2), 0);
// Put all water
// in first glass
$index = 0;
$glass[$index] = $X;
// Now let the water flow to
2577
Chapter 357. Program to find amount of water in a given glass
2578
Chapter 357. Program to find amount of water in a given glass
str_pad(findWater($i, $j,
$X), 8, '0');
// This Code is contributed by mits
?>
Output:
Source
https://www.geeksforgeeks.org/find-water-in-a-glass/
2579
Chapter 358
Pyramid form (increasing then decreasing) consecutive array using reduce operations -
GeeksforGeeks
We have N (where N > 2) stones of various heights laid out in a row. Task is to make a
pyramid from given array of stones. In a pyramid, height of the stones start from 1, increase
by 1, until it reaches some value x, then decreases by 1 until it reaches 1 again i.e. the stones
should be 1, 2, 3, 4…x – 1, x, x – 1, x – 2 … 1. All other stones not part of the pyramid should
have a height 0. We cannot move any of the stones from their current position, however, by
paying a fee of 1, we can reduce the heights of the stones. We wish to minimize the cost of
building a pyramid. Output the minimum cost to build this pyramid.
Examples:
Input : 1 2 3 4 2 1
Output : 4
The best pyramid that can be formed in this case is:
1 2 3 2 1 0
The cost is thus:
(4 - 2) + (2 - 1) + (1 - 0) = 4
Input : 1 5 2
Output : 4
We make a pyramid 1 2 1
Input : 1 2 1
Output : 0
We already have a pyramid, we do not need to do any
2580
Chapter 358. Pyramid form (increasing then decreasing) consecutive array using reduce
operations
further construction.
By using simple logic, we can prove that the pyramid with the least cost of construction
would be that of the maximum height. Also, two temples of same heights would cost the
same to construct.
This can be shown as follows:
Assume the cost of demolishing all the stones to height 0 is x.
Assume the cost of demolishing a temple of height h to height 0 is y.
Then, if it is possible to construct a temple of height h from given stones, its cost would be
x – y.
By using this, we can simplify our approach to two main steps:
1. Identify the pyramid of maximum height that can be formed.
2. Calculate the cost of constructing such a pyramid.
Step 2 can be completed in O(N) time complexity assuming we know where our pyramid is
placed.
Thus, our focus should be on decreasing the time complexity of step 1.
Naive Approach
For each position in the array, we can assume the pyramid starts at that point. We then
find the cost of constructing a temple of maximum height from 1 onwards, until a higher
height is not possible, that is, assume a pyramid of height 1 is the maximum, then assume
2 is maximum and so on. Out of each of these costs, we then choose the minimum.
This approach uses a time complexity of O(N^3).
Improved Approach
For each position, assume it is the center of a temple. Move to the left and right of this
point and attempt to find the maximum height of the temple.
This can be done by setting the maximum of height of a temple at position i to be H(i)
where H(i) is the height of the stone at that point. We then move to the left. If the height
of the stone at this point is less than H(i) – 1, we set the maximum height to now be H(i –
1) + 1. In this way we identify the maximum height for each position.
This approach uses a time complexity of O(N^2).
Dynamic Programming Approach
By modifying the above algorithm slightly, we can attempt to get an O(N) approach. Start at
the left, and moving right, find the maximum possible height pyramid that can be created
at that position. Assume that the part of the array to the right of that position is a
mirror image of the left. If H(i) is the height of stone at position i, then maxHeight(i) =
Minimum(H(i), i, maxHeight(i – 1))
This can be explained as follows:
The maximum possible height cannot exceed H(i) as we can only decrease the height of
stone, not increase.
The maximum possible height cannot exceed i, as the pyramid has to start from a height 1.
The maximum possible height cannot exceed the maximum possible height of the stone
before it – 1, as the stones have to increase by 1 for each step.
We calculate a similar value moving from right to left. We then take the minimum of these
values for each position. Then by identifying the maximum, we can calculate the minimum
cost of constructing a pyramid.
2581
Chapter 358. Pyramid form (increasing then decreasing) consecutive array using reduce
operations
2582
Chapter 358. Pyramid form (increasing then decreasing) consecutive array using reduce
operations
Output:
Source
https://www.geeksforgeeks.org/pyramid-form-increasing-decreasing-consecutive-array-using-reduce-operations/
2583
Chapter 359
Query(a, b): Find the number of sub matrices of size a X a with each of its
element consisting of the Binary Number b.
We basically need to find submatrices of given sizes with all 1s or all 0s.
Examples:
Input : N = 5, M = 4
m[][] = { { 0, 0, 1, 1 },
{ 0, 0, 1, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 }
}
Q = 2
Query 1 : a = 2, b = 1
Query 2 : a = 2, b = 0
Output : 4 1
Explanation:
For Query 1,
0011 0011 0011 0011
0010 0010 0010 0010
0111 0111 0111 0111
2584
Chapter 359. Queries on number of Binary sub-matrices of Given size
For Query 2,
0011
0010
0111
1111
0111
Input : N = 5, M = 4
m[][] = { { 0, 0, 1, 1 },
{ 0, 0, 1, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 }
}
Q = 1
Query 1 : a = 3, b = 1
Output : 1
The idea is to use Dynamic Programming to solve the problem. First declare a 2D array
dp[][], where value at dp[i][j] (say K) indicates the size of the largest square sub-matrix (K
X K) that can be formed whose all elements are equal to m[i][j] and (i, j) is the last element
(south-east) of the sub matrix. Now, dp[i][j] can be defined as:
Now, traverse the 2D dp[][] array and calculate the frequency (freq0[] for the element 0,
freq1[] for the element 1) of all the distinct values i.e distinct sizes of square sub-matrix for
both 0s and 1s.
Observe, that to count the square sub-matrix of size Y X Y, then Y+1 X Y+1 will also
contribute 1 count. Suppose we need to count 2 X 2 matrix and dp[][]=
2585
Chapter 359. Queries on number of Binary sub-matrices of Given size
...22
...23
Here, the frequency of two is 3 but observe element where dp[i][j] = 3 is also contributing a
2 X 2 square sub-matrix.
So, find the cumulative sum of the frequency for both freq0[] and freq1[].
Below is the implementation of this approach:
C++
2586
Chapter 359. Queries on number of Binary sub-matrices of Given size
+ 1;
if (max < dp[i][j])
max = dp[i][j];
}
else
dp[i][j] = 1;
}
}
int freq0[MAX] = { 0 }, freq1[MAX] = { 0 };
// Find frequency of each distinct size
// for 0s and 1s.
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == 0)
freq0[dp[i][j]]++;
else
freq1[dp[i][j]]++;
}
}
// Find the Cumulative Sum.
for (int i = max - 1; i >= 0; i--) {
freq0[i] += freq0[i + 1];
freq1[i] += freq1[i + 1];
}
// Output the answer for each query
for (int i = 0; i < q; i++) {
if (binary[i] == 0)
cout << freq0[a[i]] << endl;
else
cout << freq1[a[i]] << endl;
}
}
// Driver Program
int main()
{
int n = 5, m = 4;
int mat[N][M] = {
{ 0, 0, 1, 1 },
{ 0, 0, 1, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 1, 1 },
2587
Chapter 359. Queries on number of Binary sub-matrices of Given size
{ 0, 1, 1, 1 }
};
int q = 2;
int a[] = { 2, 2 };
int binary[] = { 1, 0 };
solveQuery(n, m, mat, q, a, binary);
return 0;
}
Java
2588
Chapter 359. Queries on number of Binary sub-matrices of Given size
2589
Chapter 359. Queries on number of Binary sub-matrices of Given size
{
int n = 5, m = 4;
int mat[][] = { { 0, 0, 1, 1 },
{ 0, 0, 1, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 } };
int q = 2;
int a[] = { 2, 2 };
int binary[] = { 1, 0 };
solveQuery(n, m, mat, q, a, binary);
}
}
// This code is contributed by anuj_67.
C#
// C# Program to answer
// queries on number of
// submatrix of given size
using System;
class GFG
{
static int MAX = 100;
// static int N = 5;
// static int M = 4;
// Return the minimum
// of three numbers
static int min(int a,
int b,
int c)
{
return Math.Min(a, Math.Min(b, c));
}
// Solve each query on matrix
static void solveQuery(int n, int m,
int [,]mat, int q,
int []a, int []binary)
{
int [,]dp = new int[n, m];
int max = 1;
// For each of the cell.
2590
Chapter 359. Queries on number of Binary sub-matrices of Given size
2591
Chapter 359. Queries on number of Binary sub-matrices of Given size
Output:
4
1
Source
https://www.geeksforgeeks.org/queries-number-binary-sub-matrices-given-size/
2592
Chapter 360
2593
Chapter 360. Queries to find distance between two nodes of a Binary tree
A sparse table will preprocess the minimum values given for an array in Nlogn space i.e.
each node will contain chain of values of log(i) length where i is the index of the ith node in
L array. Each entry in the sparse table says M[i][j] will represent the index of the minimum
value in the subarray starting at i having length 2^j.
The distance between two nodes can be obtained in terms of lowest common ancestor.
This problem can be breakdown into finding levels of each node, finding the Euler
tour of binary tree and building sparse table for LCA, these steps are explained below :
2. Find the LCA of two nodes in the binary tree in O(logn) by Storing Euler tour of
tree in array and computing two other arrays with the help of levels of each node and
Euler tour.
These steps are shown below:
(I) First, find Euler Tour of binary tree.
2594
Chapter 360. Queries to find distance between two nodes of a Binary tree
(III) Then, store First occurrences of all nodes of binary tree in Euler array.
3. Then build sparse table on L array and find the minimum value say X in range (H[A]
to H[B]). Then use the index of value X as an index to Euler array to get LCA, i.e.
Euler[index(X)].
Let, A=8 and B=5.
(I) H[8]= 1 and H[5]=2
(II) we get min value in L array between 1 and 2 as X=0, index=7
(III) Then, LCA= Euler[7], i.e LCA=1.
4. Finally, apply distance formula discussed above to get the distance between two nodes.
Source
https://www.geeksforgeeks.org/queries-find-distance-two-nodes-binary-tree/
2595
Chapter 361
Input : n = 12
Output : 13
// We break n = 12 in three parts {12/2, 12/3, 12/4}
// = {6, 4, 3}, now current sum is = (6 + 4 + 3) = 13
// again we break 6 = {6/2, 6/3, 6/4} = {3, 2, 1} = 3 +
// 2 + 1 = 6 and further breaking 3, 2 and 1 we get maximum
// summation as 1, so breaking 6 in three parts produces
// maximum sum 6 only similarly breaking 4 in three
// parts we can get maximum sum 4 and same for 3 also.
// Thus maximum sum by breaking number in parts is=13
Input : n = 24
Output : 27
// We break n = 24 in three parts {24/2, 24/3, 24/4}
// = {12, 8, 6}, now current sum is = (12 + 8 + 6) = 26
// As seen in example, recursively breaking 12 would
// produce value 13. So our maximum sum is 13 + 8 + 6 = 27.
// Note that recursively breaking 8 and 6 doesn't produce
// more values, that is why they are not broken further.
Input : n = 23
2596
Chapter 361. Recursively break a number in 3 parts to get maximum sum
Output : 23
// we break n = 23 in three parts {23/2, 23/3, 23/4} =
// {10, 7, 5}, now current sum is = (10 + 7 + 5) = 22.
// Since after further breaking we can not get maximum
// sum hence number is itself maximum i.e; answer is 23
A simple solution for this problem is to do it recursively. In each call we have to check
only max((max(n/2) + max(n/3) + max(n/4)), n) and return it. Because either we
can get maximum sum by breaking number in parts or number is itself maximum. Below
is the implementation of recursive algorithm.
C++
Java
2597
Chapter 361. Recursively break a number in 3 parts to get maximum sum
class GFG {
// Function to find the maximum sum
static int breakSum(int n)
{
// base conditions
if (n==0 || n == 1)
return n;
// recursively break the number and return
// what maximum you can get
return Math.max((breakSum(n/2) + breakSum(n/3) +
breakSum(n/4)), n);
}
// Driver program to test the above function
public static void main (String[] args) {
int n = 12;
System.out.println(breakSum(n));
}
}
// This code is contributed by Amit Kumar
C#
2598
Chapter 361. Recursively break a number in 3 parts to get maximum sum
Output :
13
An efficient solution for this problem is to use Dynamic programming because while
breaking the number in parts recursively we have to perform some overlapping problems.
For example part of n = 30 will be {15,10,7} and part of 15 will be {7,5,3} so we have to
repeat the process for 7 two times for further breaking. To avoid this overlapping problem
we are using Dynamic programming. We store values in an array and if for any number
in recursive calls we have already solution for that number currently so we diretly extract
it from array.
C++
2599
Chapter 361. Recursively break a number in 3 parts to get maximum sum
// Driver program to run the case
int main()
{
int n = 24;
cout << breakSum(n);
return 0;
}
Java
Python3
2600
Chapter 361. Recursively break a number in 3 parts to get maximum sum
C#
2601
Chapter 361. Recursively break a number in 3 parts to get maximum sum
dp[i] = Math.Max(dp[i/2] +
dp[i/3] + dp[i/4], i);
return dp[n];
}
// Driver program to test the
// above function
public static void Main ()
{
int n = 24;
Console.WriteLine(breakSum(n));
}
}
// This code is contributed by anuj_67.
Output:
27
Source
https://www.geeksforgeeks.org/recursively-break-number-3-parts-get-maximum-sum/
2602
Chapter 362
Input : arr[] = { 1, 3, 1, 5, 2 }.
Output : 43
Remove 1 from left side (score = 1*1 = 1)
then remove 2, score = 1 + 2*2 = 5
then remove 3, score = 5 + 3*3 = 14
then remove 1, score = 14 + 1*4 = 18
then remove 5, score = 18 + 5*5 = 43.
Input : arr[] = { 1, 2 }
Output : 5.
The idea is to use Dynamic Programming. Make a 2D matrix named dp[][] initialised with
0, where dp[i][j] denote the maximum value of score from index from index ito index j of
the array. So, our final result will be stored in dp[0][n-1].
Now, value for dp[i][j] will be maximum of arr[i] * (number of element already removed +
1) + dp[i+ 1][j] or arr[j] * (number of element already removed + 1) + dp[i][j – 1].
Below is the C++ implementation of this approach:
2603
Chapter 362. Remove array end element to maximize the sum of product
Output:
43
Source
https://www.geeksforgeeks.org/remove-array-end-element-maximize-sum-product/
2604
Chapter 363
Remove minimum elements from either side such that 2*min becomes more than max -
GeeksforGeeks
Given an unsorted array, trim the array such that twice of minimum is greater than maxi-
mum in the trimmed array. Elements should be removed either end of the array.
Number of removals should be minimum.
Examples:
arr[] = {4, 7, 5, 6}
Output: 0
We don't need to remove any element as
4*2 > 7 (Note that min = 4, max = 8)
arr[] = {20, 7, 5, 6}
Output: 1
We need to remove 20 so that 2*min becomes
more than max
arr[] = {20, 4, 1, 3}
2605
Chapter 363. Remove minimum elements from either side such that 2*min becomes more
than max
Output: 3
We need to remove any three elements from ends
like 20, 4, 1 or 4, 1, 3 or 20, 3, 1 or 20, 4, 1
Naive Solution:
A naive solution is to try every possible case using recurrence. Following is the naive
recursive algorithm. Note that the algorithm only returns minimum numbers of removals to
be made, it doesn’t print the trimmed array. It can be easily modified to print the trimmed
array as well.
#include <iostream>
using namespace std;
// A utility function to find minimum of two numbers
int min(int a, int b) {return (a < b)? a : b;}
// A utility function to find minimum in arr[l..h]
int min(int arr[], int l, int h)
{
int mn = arr[l];
for (int i=l+1; i<=h; i++)
if (mn > arr[i])
mn = arr[i];
return mn;
}
// A utility function to find maximum in arr[l..h]
int max(int arr[], int l, int h)
{
int mx = arr[l];
for (int i=l+1; i<=h; i++)
if (mx < arr[i])
mx = arr[i];
return mx;
}
2606
Chapter 363. Remove minimum elements from either side such that 2*min becomes more
than max
Output:
Time complexity: Time complexity of the above function can be written as following
2607
Chapter 363. Remove minimum elements from either side such that 2*min becomes more
than max
#include <iostream>
using namespace std;
// A utility function to find minimum of two numbers
int min(int a, int b) {return (a < b)? a : b;}
// A utility function to find minimum in arr[l..h]
int min(int arr[], int l, int h)
{
int mn = arr[l];
for (int i=l+1; i<=h; i++)
if (mn > arr[i])
mn = arr[i];
return mn;
}
// A utility function to find maximum in arr[l..h]
int max(int arr[], int l, int h)
{
int mx = arr[l];
for (int i=l+1; i<=h; i++)
if (mx < arr[i])
mx = arr[i];
return mx;
}
// Returns the minimum number of removals from either end
// in arr[l..h] so that 2*min becomes greater than max.
int minRemovalsDP(int arr[], int n)
{
// Create a table to store solutions of subproblems
int table[n][n], gap, i, j, mn, mx;
// Fill table using above recursive formula. Note that the table
// is filled in diagonal fashion (similar to http://goo.gl/PQqoS),
// from diagonal elements to table[0][n-1] which is the result.
for (gap = 0; gap < n; ++gap)
{
for (i = 0, j = gap; j < n; ++i, ++j)
{
mn = min(arr, i, j);
mx = max(arr, i, j);
table[i][j] = (2*mn > mx)? 0: min(table[i][j-1]+1,
table[i+1][j]+1);
}
}
return table[0][n-1];
}
2608
Chapter 363. Remove minimum elements from either side such that 2*min becomes more
than max
// Driver program to test above functions
int main()
{
int arr[] = {20, 4, 1, 3};
int n = sizeof(arr)/sizeof(arr[0]);
cout << minRemovalsDP(arr, n);
return 0;
}
2609
Chapter 363. Remove minimum elements from either side such that 2*min becomes more
than max
This article is contributed by Rahul Jain. 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/remove-minimum-elements-either-side-2min-max/
2610
Chapter 364
Input : n = 3, k = 0
Output : 2
Since k = 0, no point needs to be on its
original position. So derangements
are {3, 1, 2} and {2, 3, 1}
Input : n = 3, k = 1
Output : 3
Since k = 1, one point needs to be on its
original position. So partial derangements
are {1, 3, 2}, {3, 2, 1} and {2, 1, 3}
Input : n = 7, k = 2
Output : 924
D(0, 0) = 1
D(0, 1) = 0
2611
Chapter 364. Rencontres Number (Counting partial derangements)
Given the two positive integer n and k. The task is find rencontres number D(n, k) for giver
n and k.
Below is Recursive solution of this approach:
C++
2612
Chapter 364. Rencontres Number (Counting partial derangements)
int n = 7, m = 2;
cout << RencontresNumber(n, m) << endl;
return 0;
}
Java
2613
Chapter 364. Rencontres Number (Counting partial derangements)
Python3
2614
Chapter 364. Rencontres Number (Counting partial derangements)
# This code is contributed by Smitha Dinesh Semwal.
C#
2615
Chapter 364. Rencontres Number (Counting partial derangements)
PHP
<?php
// Recursive PHP program to
// find n-th Rencontres
// Number
// Returns value of Binomial
// Coefficient C(n, k)
function binomialCoeff($n, $k)
{
// Base Cases
if ($k == 0 || $k == $n)
return 1;
// Recurrence relation
return binomialCoeff($n - 1,$k - 1) +
binomialCoeff($n - 1, $k);
}
// Return Recontres number D(n, m)
function RencontresNumber($n, $m)
{
// base condition
if ($n == 0 && $m == 0)
return 1;
// base condition
if ($n == 1 && $m == 0)
return 0;
// base condition
if ($m == 0)
return ($n - 1) * (RencontresNumber($n - 1, 0) +
RencontresNumber($n - 2, 0));
2616
Chapter 364. Rencontres Number (Counting partial derangements)
return binomialCoeff($n, $m) *
RencontresNumber($n - $m, 0);
}
// Driver Code
$n = 7;
$m = 2;
echo RencontresNumber($n, $m),"\n";
// This code is contributed by ajit.
?>
Output:
924
C++
2617
Chapter 364. Rencontres Number (Counting partial derangements)
}
}
}
// Return Recontres number D(n, m)
int RencontresNumber(int C[][MAX], int n, int m)
{
int dp[n+1][m+1] = { 0 };
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (j <= i) {
// base case
if (i == 0 && j == 0)
dp[i][j] = 1;
// base case
else if (i == 1 && j == 0)
dp[i][j] = 0;
else if (j == 0)
dp[i][j] = (i - 1) * (dp[i - 1][0] +
dp[i - 2][0]);
else
dp[i][j] = C[i][j] * dp[i - j][0];
}
}
}
return dp[n][m];
}
// Driver Program
int main()
{
int n = 7, m = 2;
int C[MAX][MAX];
binomialCoeff(C, n, m);
cout << RencontresNumber(C, n, m) << endl;
return 0;
}
Java
2618
Chapter 364. Rencontres Number (Counting partial derangements)
// Number
import java.io.*;
class GFG {
static int MAX = 100;
// Fills table C[n+1][k+1] such that C[i][j]
// represents table of binomial coefficient
// iCj
static void binomialCoeff(int C[][], int n, int k)
{
// Calculate value of Binomial Coefficient
// in bottom up manner
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, k); j++)
{
// Base Cases
if (j == 0 || j == i)
C[i][j] = 1;
// Calculate value using previously
// stored values
else
C[i][j] = C[i - 1][j - 1] +
C[i - 1][j];
}
}
}
// Return Recontres number D(n, m)
static int RencontresNumber(int C[][], int n, int m)
{
int dp[][] = new int[n + 1][m + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (j <= i) {
// base case
if (i == 0 && j == 0)
dp[i][j] = 1;
// base case
else if (i == 1 && j == 0)
2619
Chapter 364. Rencontres Number (Counting partial derangements)
dp[i][j] = 0;
else if (j == 0)
dp[i][j] = (i - 1) * (dp[i - 1][0]
+ dp[i - 2][0]);
else
dp[i][j] = C[i][j] * dp[i - j][0];
}
}
}
return dp[n][m];
}
// Driver Program
public static void main(String[] args)
{
int n = 7, m = 2;
int C[][] = new int[MAX][MAX];
binomialCoeff(C, n, m);
System.out.println(RencontresNumber(C, n, m));
}
}
// This code is contributed by vt_m.
Python 3
2620
Chapter 364. Rencontres Number (Counting partial derangements)
# Calculate value using previously
# stored values
else :
C[i][j] = (C[i - 1][j - 1]
+ C[i - 1][j])
# Return Recontres number D(n, m)
def RencontresNumber(C, n, m) :
w, h = m+1, n+1
dp= [[0 for x in range(w)] for y in range(h)]
for i in range(0, n+1) :
for j in range(0, m+1) :
if (j <= i) :
# base case
if (i == 0 and j == 0) :
dp[i][j] = 1
# base case
elif (i == 1 and j == 0) :
dp[i][j] = 0
elif (j == 0) :
dp[i][j] = ((i - 1) *
(dp[i - 1][0] + dp[i - 2][0]))
else :
dp[i][j] = C[i][j] * dp[i - j][0]
return dp[n][m]
# Driver Program
n = 7
m = 2
C = [[0 for x in range(MAX)] for y in range(MAX)]
binomialCoeff(C, n, m)
print(RencontresNumber(C, n, m))
# This code is contributed by Nikita Tiwari.
C#
2621
Chapter 364. Rencontres Number (Counting partial derangements)
// DP based C# program
// to find n-th Rencontres
// Number
using System;
class GFG
{
static int MAX = 100;
// Fills table C[n+1][k+1]
// such that C[i][j]
// represents table of
// binomial coefficient iCj
static void binomialCoeff(int [,]C,
int n, int k)
{
// Calculate value of
// Binomial Coefficient
// in bottom up manner
for (int i = 0; i <= n; i++)
{
for (int j = 0;
j <= Math.Min(i, k); j++)
{
// Base Cases
if (j == 0 || j == i)
C[i,j] = 1;
// Calculate value using
// previously stored values
else
C[i, j] = C[i - 1, j - 1] +
C[i - 1, j];
}
}
}
// Return Recontres
// number D(n, m)
static int RencontresNumber(int [,]C,
int n, int m)
{
int [,]dp = new int[n + 1,
m + 1];
for (int i = 0; i <= n; i++)
2622
Chapter 364. Rencontres Number (Counting partial derangements)
{
for (int j = 0; j <= m; j++)
{
if (j <= i)
{
// base case
if (i == 0 && j == 0)
dp[i, j] = 1;
// base case
else if (i == 1 && j == 0)
dp[i, j] = 0;
else if (j == 0)
dp[i, j] = (i - 1) *
(dp[i - 1, 0] +
dp[i - 2, 0]);
else
dp[i, j] = C[i, j] *
dp[i - j, 0];
}
}
}
return dp[n, m];
}
// Driver Code
static public void Main ()
{
int n = 7, m = 2;
int [,]C = new int[MAX, MAX];
binomialCoeff(C, n, m);
Console.WriteLine(RencontresNumber(C, n, m));
}
}
// This code is contributed
// by akt_mit
Output:
924
2623
Chapter 364. Rencontres Number (Counting partial derangements)
Source
https://www.geeksforgeeks.org/rencontres-number-counting-partial-derangements/
2624
Chapter 365
Semiperfect Number
Input: 40
Output: The number is Semiperfect
1+4+5+10+20=40
Input: 70
Output: The number is not Semiperfect
The first few semiperfect numbers are
6, 12, 18, 20, 24, 28, 30, 36, 40
2625
Chapter 365. Semiperfect Number
2626
Chapter 365. Semiperfect Number
subset[0][i] = false;
// loop to find whther the number is semiperfect
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= n; j++) {
// calculation to check if the
// number can be made by summation of diviors
if (j < v[i - 1])
subset[i][j] = subset[i - 1][j];
else {
subset[i][j] = subset[i - 1][j] ||
subset[i - 1][j - v[i - 1]];
}
}
}
// if not possible to make the
// number by any combination of divisors
if ((subset[r][n]) == 0)
return false;
else
return true;
}
// driver code to check if possible
int main()
{
int n = 40;
if (check(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/semiperfect-number/
2627
Chapter 366
2628
Chapter 366. Sequence Alignment problem
that the addition of extra gaps after equalising the lengths will only lead to increment of
penalty.
Optimal Substructure
It can be observed from an optimal solution, for example from the given sample input, that
the optimal solution narrows down to only three candidates.
1. and .
2. and gap.
3. gap and .
Proof of Optimal Substructure.
Let be the penalty of the optimal alignment of and . Then, from the
optimal substructure,
.
2. When
2629
Chapter 366. Sequence Alignment problem
using namespace std;
// function to find out the minimum penalty
void getMinimumPenalty(string x, string y, int pxy, int pgap)
{
int i, j; // intialising variables
int m = x.length(); // length of gene1
int n = y.length(); // length of gene2
// table for storing optimal substructure answers
int dp[n+m+1][n+m+1] = {0};
// intialising the table
for (i = 0; i <= (n+m); i++)
{
dp[i][0] = i * pgap;
dp[0][i] = i * pgap;
}
// calcuting the minimum penalty
for (i = 1; i <= m; i++)
{
for (j = 1; j <= n; j++)
{
if (x[i - 1] == y[j - 1])
{
dp[i][j] = dp[i - 1][j - 1];
}
else
{
dp[i][j] = min({dp[i - 1][j - 1] + pxy ,
dp[i - 1][j] + pgap ,
dp[i][j - 1] + pgap });
}
}
}
// Reconstructing the solution
int l = n + m; // maximum possible length
i = m; j = n;
int xpos = l;
int ypos = l;
// Final answers for the respective strings
2630
Chapter 366. Sequence Alignment problem
2631
Chapter 366. Sequence Alignment problem
{
id = i + 1;
break;
}
}
// Printing the final answer
cout << "Minimum Penalty in aligning the genes = ";
cout << dp[m][n] << "\n";
cout << "The aligned genes are :\n";
for (i = id; i <= l; i++)
{
cout<<(char)xans[i];
}
cout << "\n";
for (i = id; i <= l; i++)
{
cout << (char)yans[i];
}
return;
}
// Driver code
int main(){
// input strings
string gene1 = "AGGGCT";
string gene2 = "AGGCA";
// intialsing penalties of different types
int misMatchPenalty = 3;
int gapPenalty = 2;
// calling the function to calculate the result
getMinimumPenalty(gene1, gene2,
misMatchPenalty, gapPenalty);
return 0;
}
Java
2632
Chapter 366. Sequence Alignment problem
2633
Chapter 366. Sequence Alignment problem
int xpos = l;
int ypos = l;
// Final answers for
// the respective strings
int xans[] = new int[l + 1];
int yans[] = new int[l + 1];
while ( !(i == 0 || j == 0))
{
if (x.charAt(i - 1) == y.charAt(j - 1))
{
xans[xpos--] = (int)x.charAt(i - 1);
yans[ypos--] = (int)y.charAt(j - 1);
i--; j--;
}
else if (dp[i - 1][j - 1] + pxy == dp[i][j])
{
xans[xpos--] = (int)x.charAt(i - 1);
yans[ypos--] = (int)y.charAt(j - 1);
i--; j--;
}
else if (dp[i - 1][j] + pgap == dp[i][j])
{
xans[xpos--] = (int)x.charAt(i - 1);
yans[ypos--] = (int)'_';
i--;
}
else if (dp[i][j - 1] + pgap == dp[i][j])
{
xans[xpos--] = (int)'_';
yans[ypos--] = (int)y.charAt(j - 1);
j--;
}
}
while (xpos > 0)
{
if (i > 0) xans[xpos--] = (int)x.charAt(--i);
else xans[xpos--] = (int)'_';
}
while (ypos > 0)
{
if (j > 0) yans[ypos--] = (int)y.charAt(--j);
else yans[ypos--] = (int)'_';
}
// Since we have assumed the
// answer to be n+m long,
2634
Chapter 366. Sequence Alignment problem
2635
Chapter 366. Sequence Alignment problem
misMatchPenalty, gapPenalty);
}
}
PHP
<?php
// PHP program to implement
// sequence alignment problem.
// function to find out
// the minimum penalty
function getMinimumPenalty($x, $y,
$pxy, $pgap)
{
$i; $j; // intializing variables
$m = strlen($x); // length of gene1
$n = strlen($y); // length of gene2
// table for storing optimal
// substructure answers
$dp[$n + $m + 1][$n + $m + 1] = array(0);
// intialising the table
for ($i = 0; $i <= ($n+$m); $i++)
{
$dp[$i][0] = $i * $pgap;
$dp[0][$i] = $i * $pgap;
}
// calcuting the
// minimum penalty
for ($i = 1; $i <= $m; $i++)
{
for ($j = 1; $j <= $n; $j++)
{
if ($x[$i - 1] == $y[$j - 1])
{
$dp[$i][$j] = $dp[$i - 1][$j - 1];
}
else
{
$dp[$i][$j] = min($dp[$i - 1][$j - 1] + $pxy ,
$dp[$i - 1][$j] + $pgap ,
$dp[$i][$j - 1] + $pgap );
}
}
2636
Chapter 366. Sequence Alignment problem
}
// Reconstructing the solution
$l = $n + $m; // maximum possible length
$i = $m; $j = $n;
$xpos = $l;
$ypos = $l;
// Final answers for
// the respective strings
// $xans[$l + 1]; $yans[$l + 1];
while ( !($i == 0 || $j == 0))
{
if ($x[$i - 1] == $y[$j - 1])
{
$xans[$xpos--] = $x[$i - 1];
$yans[$ypos--] = $y[$j - 1];
$i--; $j--;
}
else if ($dp[$i - 1][$j - 1] +
$pxy == $dp[$i][$j])
{
$xans[$xpos--] = $x[$i - 1];
$yans[$ypos--] = $y[$j - 1];
$i--; $j--;
}
else if ($dp[$i - 1][$j] +
$pgap == $dp[$i][$j])
{
$xans[$xpos--] = $x[$i - 1];
$yans[$ypos--] = '_';
$i--;
}
else if ($dp[$i][$j - 1] +
$pgap == $dp[$i][$j])
{
$xans[$xpos--] = '_';
$yans[$ypos--] = $y[$j - 1];
$j--;
}
}
while ($xpos > 0)
{
if ($i > 0) $xans[$xpos--] = $x[--$i];
else $xans[$xpos--] = '_';
2637
Chapter 366. Sequence Alignment problem
}
while ($ypos > 0)
{
if ($j > 0)
$yans[$ypos--] = $y[--$j];
else
$yans[$ypos--] = '_';
}
// Since we have assumed the
// answer to be n+m long,
// we need to remove the extra
// gaps in the starting
// id represents the index
// from which the arrays
// xans, yans are useful
$id = 1;
for ($i = $l; $i >= 1; $i--)
{
if ($yans[$i] == '_' &&
$xans[$i] == '_')
{
$id = $i + 1;
break;
}
}
// Printing the final answer
echo "Minimum Penalty in ".
"aligning the genes = ";
echo $dp[$m][$n] . "\n";
echo "The aligned genes are :\n";
for ($i = $id; $i <= $l; $i++)
{
echo $xans[$i];
}
echo "\n";
for ($i = $id; $i <= $l; $i++)
{
echo $yans[$i];
}
return;
}
// Driver code
// input strings
$gene1 = "AGGGCT";
2638
Chapter 366. Sequence Alignment problem
$gene2 = "AGGCA";
// intialsing penalties
// of different types
$misMatchPenalty = 3;
$gapPenalty = 2;
// calling the function
// to calculate the result
getMinimumPenalty($gene1, $gene2,
$misMatchPenalty, $gapPenalty);
// This code is contributed by Abhinav96
?>
Output:
Time Complexity :
Space Complexity :
Improved By : AayushChaturvedi
Source
https://www.geeksforgeeks.org/sequence-alignment-problem/
2639
Chapter 367
Sequences of given length where every element is more than or equal to twice of previous -
GeeksforGeeks
Given two integers m & n, find the number of possible sequences of length n such that each
of the next element is greater than or equal to twice of the previous element but less than
or equal to m.
Examples :
Input : m = 10, n = 4
Output : 4
There should be n elements and value of last
element should be at-most m.
The sequences are {1, 2, 4, 8}, {1, 2, 4, 9},
{1, 2, 4, 10}, {1, 2, 5, 10}
Input : m = 5, n = 2
Output : 6
The sequences are {1, 2}, {1, 3}, {1, 4},
{1, 5}, {2, 4}, {2, 5}
As per the given condition the n-th value of the sequence can be at most m. There can be
two cases for n-th element:
1. If it is m, then the (n-1)th element is at most m/2. We recur for m/2 and n-1.
2. If it is not m, then the n-1th element is at most is m-1. We recur for (m-1) and n.
2640
Chapter 367. Sequences of given length where every element is more than or equal to twice
of previous
The total number of sequences is the sum of the number of sequences including m and the
number of sequences where m is not included. Thus the original problem of finding number
of sequences of length n with max value m can be subdivided into independent subproblems
of finding number of sequences of length n with max value m-1 and number of sequences of
length n-1 with max value m/2.
C++
Java
2641
Chapter 367. Sequences of given length where every element is more than or equal to twice
of previous
C#
2642
Chapter 367. Sequences of given length where every element is more than or equal to twice
of previous
// If n is 0, found an empty special sequence
if(n == 0)
return 1;
// There can be two possibilities : (1) Reduce
// last element value (2) Consider last element
// as m and reduce number of terms
return getTotalNumberOfSequences (m-1, n) +
getTotalNumberOfSequences (m/2, n-1);
}
// Driver code
public static void Main ()
{
int m = 10;
int n = 4;
Console.Write("Total number of possible sequences " +
getTotalNumberOfSequences(m, n));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to count total
// number of special sequences
// of length n where
// Recursive function to find
// the number of special sequences
function getTotalNumberOfSequences($m, $n)
{
// A special sequence cannot
// exist if length n is more
// than the maximum value m.
if ($m < $n)
return 0;
// If n is 0, found an empty
// special sequence
if ($n == 0)
return 1;
// There can be two possibilities :
2643
Chapter 367. Sequences of given length where every element is more than or equal to twice
of previous
Output:
Note that the above function computes the same sub problems again and again. Consider
the following tree for f(10, 4).
2644
Chapter 367. Sequences of given length where every element is more than or equal to twice
of previous
2645
Chapter 367. Sequences of given length where every element is more than or equal to twice
of previous
int m = 10;
int n = 4;
printf("Total number of possible sequences %d",
getTotalNumberOfSequences(m, n));
return 0;
}
Java
2646
Chapter 367. Sequences of given length where every element is more than or equal to twice
of previous
C#
2647
Chapter 367. Sequences of given length where every element is more than or equal to twice
of previous
// if length of sequence
// is more than the maximum
// value, special sequence
// cannot exist
else if (i < j)
T[i,j] = 0;
// If length of sequence is 1 then the
// number of special sequences is equal
// to the maximum value
// For example with maximum value 2 and
// length 1, there can be 2 special
// sequences {1}, {2}
else if (j == 1)
T[i,j] = i;
// otherwise calculate
else
T[i,j] = T[i - 1, j] + T[i / 2, j - 1];
}
}
return T[m,n];
}
// Driver Code
public static void Main ()
{
int m = 10;
int n = 4;
Console.WriteLine("Total number of possible sequences "+
getTotalNumberOfSequences(m, n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to count total
// number of special sequences
// of length N where
// DP based function to find
// the number of special
// sequences
function getTotalNumberOfSequences($m, $n)
2648
Chapter 367. Sequences of given length where every element is more than or equal to twice
of previous
{
// define T and build in bottom
// manner to store number of
// special sequences of length
// n and maximum value m
$T = array(array());
for ($i = 0; $i < $m + 1; $i++)
{
for ($j = 0; $j < $n + 1; $j++)
{
// Base case : If length of
// sequence is 0 or maximum
// value is 0, there cannot
// exist any special sequence
if ($i == 0 or $j == 0)
$T[$i][$j] = 0;
// if length of sequence is
// more than the maximum value,
// special sequence cannot exist
else if ($i < $j)
$T[$i][$j] = 0;
// If length of sequence is
// 1 then the number of
// special sequences is equal
// to the maximum value
// For example with maximum
// value 2 and length 1, there
// can be 2 special sequences
// {1}, {2}
else if ($j == 1)
$T[$i][$j] = $i;
// otherwise calculate
else
$T[$i][$j] = $T[$i - 1][$j] +
$T[$i / 2][$j - 1];
}
}
return $T[$m][$n];
}
// Driver Code
$m = 10;
2649
Chapter 367. Sequences of given length where every element is more than or equal to twice
of previous
$n = 4;
echo "Total number of possible sequences ",
getTotalNumberOfSequences($m, $n);
// This code is contributed by anuj_67.
?>
Output:
Source
https://www.geeksforgeeks.org/sequences-given-length-every-element-equal-twice-previous/
2650
Chapter 368
Shortest Common
Supersequence
This problem is closely related to longest common subsequence problem. Below are steps.
1) Find Longest Common Subsequence (lcs) of two given strings. For example, lcs of “geek”
and “eke” is “ek”.
2) Insert non-lcs characters (in their original order in strings) to the lcs found above, and
return the result. So “ek” becomes “geeke” which is shortest common supersequence.
Let us consider another example, str1 = “AGGTAB” and str2 = “GXTXAYB”. LCS of str1
and str2 is “GTAB”. Once we find LCS, we insert characters of both strings in order and
we get “AGXGTXAYB”
How does this work?
We need to find a string that has both strings as subsequences and is shortest such string. If
both strings have all characters different, then result is sum of lengths of two given strings.
If there are common characters, then we don’t want them multiple times as the task is
to minimize length. Therefore, we fist find the longest common subsequence, take one
occurrence of this subsequence and add extra characters.
2651
Chapter 368. Shortest Common Supersequence
Below is the implementation of above idea. The below implementation only finds length of
the shortest supersequence.
2652
Chapter 368. Shortest Common Supersequence
int i, j;
// Following steps build L[m + 1][n + 1]
// in bottom up fashion. Note that
// L[i][j] contains length of LCS of
// X[0..i - 1] and Y[0..j - 1]
for (i = 0; i <= m; i++)
{
for (j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i - 1] == Y[j - 1])
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = max(L[i - 1][j],
L[i][j - 1]);
}
}
// L[m][n] contains length of LCS
// for X[0..n - 1] and Y[0..m - 1]
return L[m][n];
}
// Driver code
int main()
{
char X[] = "AGGTAB";
char Y[] = "GXTXAYB";
printf("Length of the shortest supersequence is %d\n",
shortestSuperSequence(X, Y));
return 0;
}
Java
2653
Chapter 368. Shortest Common Supersequence
2654
Chapter 368. Shortest Common Supersequence
Python3
2655
Chapter 368. Shortest Common Supersequence
C#
2656
Chapter 368. Shortest Common Supersequence
Output:
2657
Chapter 368. Shortest Common Supersequence
if (m == 0) return n;
if (n == 0) return m;
C++
Java
2658
Chapter 368. Shortest Common Supersequence
Python3
2659
Chapter 368. Shortest Common Supersequence
C#
Output:
Time complexity of the above solution exponential O(2min(m, n) ). Since there are over-
lapping subproblems, we can efficiently solve this recursive problem using Dynamic
Programming. Below is Dynamic Programming based implementation. Time complexity
of this solution is O(mn).
C++
2660
Chapter 368. Shortest Common Supersequence
Java
2661
Chapter 368. Shortest Common Supersequence
Python3
2662
Chapter 368. Shortest Common Supersequence
# Fill table in bottom up manner
for i in range(m + 1):
for j in range(n + 1):
#Below steps follow above recurrence
if (not i): dp[i][j] = j
elif (not j): dp[i][j] = i
elif (X[i - 1] == Y[j - 1]):
dp[i][j] = 1 + dp[i - 1][j - 1]
else: dp[i][j] = 1 + min(dp[i - 1][j],
dp[i][j - 1])
return dp[m][n]
# Driver Code
X = "AGGTAB"
Y = "GXTXAYB"
print("Length of the shortest supersequence is %d"
% superSeq(X, Y, len(X), len(Y)))
# This code is contributed by Ansu Kumari
C#
2663
Chapter 368. Shortest Common Supersequence
else if (j == 0)
dp[i, j] = i;
else if (X[i - 1] == Y[j - 1])
dp[i, j] = 1 + dp[i - 1, j - 1];
else
dp[i, j] = 1 + Math.Min(dp[i - 1, j],
dp[i, j - 1]);
}
}
return dp[m, n];
}
// Driver code
public static void Main()
{
String X = "AGGTAB";
String Y = "GXTXAYB";
Console.WriteLine("Length of the shortest supersequence is "
+ superSeq(X, Y, X.Length,Y.Length));
}
}
// This code is contributed by Sam007
Output:
Source
https://www.geeksforgeeks.org/shortest-common-supersequence/
2664
Chapter 369
Shortest Uncommon
Subsequence
2665
Chapter 369. Shortest Uncommon Subsequence
1.Optimal substructure : Consider two strings S and T of length m and n respectively &
let the function to find the shortest uncommon subsequence be shortestSeq (char *S, char
*T). For each character in S, if it is not present in T then that character is the answer itself.
Otherwise if it is found at index k then we have the choice of either including it in the
shortest uncommon subsequence or not.
Thus we can see that this problem has optimal substructure property as it can be solved by
using solution to sub problems.
2.Overlapping Sub problems
Following is a simple recursive implementation of the above problem.
2666
Chapter 369. Shortest Uncommon Subsequence
If we draw the complete recursion tree, then we can see that there are many sub problems
which are solved again and again. So this problem has Overlapping Substructure property
and recomputation of same sub problems can be avoided by either using Memoization or
Tabulation. Following is a tabulated implementation for the problem.
2667
Chapter 369. Shortest Uncommon Subsequence
2668
Chapter 369. Shortest Uncommon Subsequence
Output:
Source
https://www.geeksforgeeks.org/shortest-uncommon-subsequence/
2669
Chapter 370
Shortest path with exactly k edges in a directed and weighted graph - GeeksforGeeks
Given a directed and two vertices ‘u’ and ‘v’ in it, find shortest path from ‘u’ to ‘v’ with
exactly k edges on the path.
The graph is given as adjacency matrix representation where value of graph[i][j] indicates
the weight of an edge from vertex i to vertex j and a value INF(infinite) indicates no edge
from i to j.
For example consider the following graph. Let source ‘u’ be vertex 0, destination ‘v’ be 3
and k be 2. There are two walks of length 2, the walks are {0, 2, 3} and {0, 1, 3}. The
shortest among the two is {0, 2, 3} and weight of path is 3+6 = 9.
The idea is to browse through all paths of length k from u to v using the approach discussed
in the previous post and return weight of the shortest path. A simple solution is to start
2670
Chapter 370. Shortest path with exactly k edges in a directed and weighted graph
from u, go to all adjacent vertices and recur for adjacent vertices with k as k-1, source as
adjacent vertex and destination as v. Following are C++ and Java implementations of this
simple solution.
C++
2671
Chapter 370. Shortest path with exactly k edges in a directed and weighted graph
Java
2672
Chapter 370. Shortest path with exactly k edges in a directed and weighted graph
Output:
The worst case time complexity of the above function is O(Vk ) where V is the number of
vertices in the given graph. We can simply analyze the time complexity by drawing recursion
tree. The worst occurs for a complete graph. In worst case, every internal node of recursion
tree would have exactly V children.
We can optimize the above solution using Dynamic Programming. The idea is to build
a 3D table where first dimension is source, second dimension is destination, third dimension
is number of edges from source to destination, and the value is count of walks. Like other
Dynamic Programming problems, we fill the 3D table in bottom up manner.
C++
2673
Chapter 370. Shortest path with exactly k edges in a directed and weighted graph
{
for (int j = 0; j < V; j++) // for destination
{
// initialize value
sp[i][j][e] = INF;
// from base cases
if (e == 0 && i == j)
sp[i][j][e] = 0;
if (e == 1 && graph[i][j] != INF)
sp[i][j][e] = graph[i][j];
//go to adjacent only when number of edges is more than 1
if (e > 1)
{
for (int a = 0; a < V; a++)
{
// There should be an edge from i to a and a
// should not be same as either i or j
if (graph[i][a] != INF && i != a &&
j!= a && sp[a][j][e-1] != INF)
sp[i][j][e] = min(sp[i][j][e], graph[i][a] +
sp[a][j][e-1]);
}
}
}
}
}
return sp[u][v][k];
}
// driver program to test above function
int main()
{
/* Let us create the graph shown in above diagram*/
int graph[V][V] = { {0, 10, 3, 2},
{INF, 0, INF, 7},
{INF, INF, 0, 6},
{INF, INF, INF, 0}
};
int u = 0, v = 3, k = 2;
cout << shortestPath(graph, u, v, k);
return 0;
}
Java
2674
Chapter 370. Shortest path with exactly k edges in a directed and weighted graph
// exactly k edges
import java.util.*;
import java.lang.*;
import java.io.*;
class ShortestPath
{
// Define number of vertices in the graph and inifinite value
static final int V = 4;
static final int INF = Integer.MAX_VALUE;
// A Dynamic programming based function to find the shortest path
// from u to v with exactly k edges.
int shortestPath(int graph[][], int u, int v, int k)
{
// Table to be filled up using DP. The value sp[i][j][e] will
// store weight of the shortest path from i to j with exactly
// k edges
int sp[][][] = new int[V][V][k+1];
// Loop for number of edges from 0 to k
for (int e = 0; e <= k; e++)
{
for (int i = 0; i < V; i++) // for source
{
for (int j = 0; j < V; j++) // for destination
{
// initialize value
sp[i][j][e] = INF;
// from base cases
if (e == 0 && i == j)
sp[i][j][e] = 0;
if (e == 1 && graph[i][j] != INF)
sp[i][j][e] = graph[i][j];
// go to adjacent only when number of edges is
// more than 1
if (e > 1)
{
for (int a = 0; a < V; a++)
{
// There should be an edge from i to a and
// a should not be same as either i or j
if (graph[i][a] != INF && i != a &&
j!= a && sp[a][j][e-1] != INF)
sp[i][j][e] = Math.min(sp[i][j][e],
graph[i][a] + sp[a][j][e-1]);
2675
Chapter 370. Shortest path with exactly k edges in a directed and weighted graph
}
}
}
}
}
return sp[u][v][k];
}
public static void main (String[] args)
{
/* Let us create the graph shown in above diagram*/
int graph[][] = new int[][]{ {0, 10, 3, 2},
{INF, 0, INF, 7},
{INF, INF, 0, 6},
{INF, INF, INF, 0}
};
ShortestPath t = new ShortestPath();
int u = 0, v = 3, k = 2;
System.out.println("Weight of the shortest path is "+
t.shortestPath(graph, u, v, k));
}
}
//This code is contributed by Aakash Hasija
Output:
Time complexity of the above DP based solution is O(V3 K) which is much better than the
naive solution.
This article is contributed by Abhishek. 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-path-exactly-k-edges-directed-weighted-graph/
2676
Chapter 371
Input : a = "pear"
b = "peach"
Output : pearch
pearch is the shorted string such that both
pear and peach are its subsequences.
Input : a = "geek"
b = "code"
Output : gecodek
We have discussed a solution to find length of the shortest supersequence in below post.
Shortest Common Supersequence
In this post, printing of supersequence is discussed. The solution is based on below recursive
approach discussed in above post as an alternate method.
if (m == 0) return n;
if (n == 0) return m;
2677
Chapter 371. Shortest possible combination of two strings
We build a DP array to store lengths. After building the DP array, we traverse from bottom
right most position. The approach of printing is similar to printing LCS.
C++
2678
Chapter 371. Shortest possible combination of two strings
2679
Chapter 371. Shortest possible combination of two strings
return 0;
}
Java
2680
Chapter 371. Shortest possible combination of two strings
// reduce values of i, j and indexs
i--;
j--;
}
// If not same, then find the larger of two and
// go in the direction of larger value
else if (dp[i-1][j] < dp[i][j-1])
{
res = a.charAt(i-1) + res;
i--;
}
else
{
res = b.charAt(j-1) + res;
j--;
}
}
// Copy remaining characters of string 'a'
while (i > 0)
{
res = a.charAt(i-1) + res;
i--;
}
// Copy remaining characters of string 'b'
while (j > 0)
{
res = b.charAt(j-1) + res;
j--;
}
// Print the result
System.out.println(res);
}
/* Driver program to test above function */
public static void main(String args[])
{
String a = "algorithm";
String b = "rhythm";
printSuperSeq(a, b);
}
}
// This article is contributed by Sumit Ghosh
2681
Chapter 371. Shortest possible combination of two strings
Output:
algorihythm
C++
2682
Chapter 371. Shortest possible combination of two strings
} else {
index(dp, a, b, size_a, size_b - 1);
}
}
}
// function to combine the strings to form
// the shortest string
void combine(string a, string b, int size_a,
int size_b)
{
int dp[100][100];
string ans = "";
int k = 0;
// Initialize the matrix to 0
memset(dp, 0, sizeof(dp));
// Store the increment of diagonally
// previous value if a[i-1] and b[j-1] are
// equal, else store the max of dp[i][j-1]
// and dp[i-1][j]
for (int i = 1; i <= size_a; i++) {
for (int j = 1; j <= size_b; j++) {
if (a[i - 1] == b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i][j - 1],
dp[i - 1][j]);
}
}
}
// Get the Lowest Common Subsequence
int lcs = dp[size_a][size_b];
// Backtrack the dp array to get the index
// vectors of two strings, used to find
// the shortest possible combination.
index(dp, a, b, size_a, size_b);
int i, j = i = k;
// Build the string combination using the
// index found by backtracking
while (k < lcs) {
while (i < size_a && i < index_a[k]) {
2683
Chapter 371. Shortest possible combination of two strings
ans += a[i++];
}
while (j < size_b && j < index_b[k]) {
ans += b[j++];
}
ans = ans + a[index_a[k]];
k++;
i++;
j++;
}
// Append the remaining characters in a
// to answer
while (i < size_a) {
ans += a[i++];
}
// Append the remaining characters in b
// to answer
while (j < size_b) {
ans += b[j++];
}
cout << ans;
}
// Driver code
int main()
{
string a = "algorithm";
string b = "rhythm";
// Store the length of string
int size_a = a.size();
int size_b = b.size();
combine(a, b, size_a, size_b);
return 0;
}
Java
2684
Chapter 371. Shortest possible combination of two strings
// Vector that store the index of string a and b
static ArrayList<Integer> index_a = new ArrayList<>();
static ArrayList<Integer> index_b = new ArrayList<>();
// Subroutine to Backtrack the dp matrix to
// find the index vector traversing which would
// yield the shortest possible combination
static void index(int dp[][], String a, String b,
int size_a, int size_b)
{
// Clear the index vectors
index_a.clear();
index_b.clear();
// Return if either of a or b is reduced
// to 0
if (size_a == 0 || size_b == 0)
return;
// Push both to index_a and index_b with
// the respective a and b index
if (a.charAt(size_a - 1) == b.charAt(size_b - 1)) {
index(dp, a, b, size_a - 1, size_b - 1);
index_a.add(size_a - 1);
index_b.add(size_b - 1);
} else {
if (dp[size_a - 1][size_b] > dp[size_a]
[size_b - 1]) {
index(dp, a, b, size_a - 1, size_b);
} else {
index(dp, a, b, size_a, size_b - 1);
}
}
}
// function to combine the strings to form
// the shortest string
static void combine(String a, String b, int size_a,
int size_b)
{
int[][] dp = new int[100][100];
String ans = "";
int k = 0;
// Store the increment of diagonally
// previous value if a[i-1] and b[j-1] are
2685
Chapter 371. Shortest possible combination of two strings
2686
Chapter 371. Shortest possible combination of two strings
Output:
algorihythm
Source
https://www.geeksforgeeks.org/shortest-possible-combination-two-strings/
2687
Chapter 372
Sieve of Eratosthenes
Input : n =10
Output : 2 3 5 7
Input : n = 20
Output: 2 3 5 7 11 13 17 19
The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n
when n is smaller than 10 million or so (Ref Wiki).
Following is the algorithm to find all the prime numbers less than or equal to a given
integer n by Eratosthenes’ method:
When the algorithm terminates, all the numbers in the list that are not marked are prime.
Explanation with Example:
Let us take an example when n = 50. So we need to print all print numbers smaller than
or equal to 50.
2688
Chapter 372. Sieve of Eratosthenes
According to the algorithm we will mark all the numbers which are divisible by 2.
Now we move to our next unmarked number 3 and mark all the numbers which are
multiples of 3.
We continue this process and our final table will look like below:
2689
Chapter 372. Sieve of Eratosthenes
So the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47.
Thanks toKrishan Kumar for providing above explanation.
Implementation:
Following is the implementation of the above algorithm. In the following implementation,
a boolean array arr[] of size n is used to mark multiples of prime numbers.
C/C++
2690
Chapter 372. Sieve of Eratosthenes
}
// Driver Program to test above function
int main()
{
int n = 30;
cout << "Following are the prime numbers smaller "
<< " than or equal to " << n << endl;
SieveOfEratosthenes(n);
return 0;
}
Java
2691
Chapter 372. Sieve of Eratosthenes
Python
C#
2692
Chapter 372. Sieve of Eratosthenes
2693
Chapter 372. Sieve of Eratosthenes
PHP
<?php
// php program to print all primes smaller
// than or equal to n using Sieve of
// Eratosthenes
function SieveOfEratosthenes($n)
{
// Create a boolean array "prime[0..n]"
// and initialize all entries it as true.
// A value in prime[i] will finally be
// false if i is Not a prime, else true.
$prime = array_fill(0, $n+1, true);
for ($p = 2; $p*$p <= $n; $p++)
{
// If prime[p] is not changed,
// then it is a prime
if ($prime[$p] == true)
{
// Update all multiples of p
for ($i = $p*2; $i <= $n; $i += $p)
$prime[$i] = false;
}
}
// Print all prime numbers
for ($p = 2; $p <= $n; $p++)
if ($prime[$p])
echo $p." ";
}
// Driver Program to test above function
$n = 30;
echo "Following are the prime numbers "
."smaller than or equal to " .$n."\n" ;
2694
Chapter 372. Sieve of Eratosthenes
SieveOfEratosthenes($n);
// This code is contributed by mits
?>
Output:
Source
https://www.geeksforgeeks.org/sieve-of-eratosthenes/
2695
Chapter 373
2696
Chapter 373. Size of The Subarray With Maximum Sum
Java
2697
Chapter 373. Size of The Subarray With Maximum Sum
if (max_so_far < max_ending_here)
{
max_so_far = max_ending_here;
start = s;
end = i;
}
if (max_ending_here < 0)
{
max_ending_here = 0;
s = i + 1;
}
}
return (end - start + 1);
}
// Driver code
public static void main(String[] args)
{
int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
int n = a.length;
System.out.println(maxSubArraySum(a, n));
}
}
Python3
2698
Chapter 373. Size of The Subarray With Maximum Sum
start = s
end = i
if max_ending_here < 0:
max_ending_here = 0
s = i+1
return (end - start + 1)
# Driver program to test maxSubArraySum
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print(maxSubArraySum(a,len(a)))
C#
2699
Chapter 373. Size of The Subarray With Maximum Sum
PHP
<?php
// PHP program for Bresenham’s
// Line Generation Assumptions :
// 1) Line is drawn from
// left to right.
// 2) x1 < x2 and y1 < y2
// 3) Slope of the line is
// between 0 and 1.
// We draw a line from lower
// left to upper right.
// function for line generation
function bresenham($x1, $y1, $x2, $y2)
{
$m_new = 2 * ($y2 - $y1);
$slope_error_new = $m_new - ($x2 - $x1);
for ($x = $x1, $y = $y1; $x <= $x2; $x++)
{
echo "(" ,$x , "," , $y, ")\n";
// Add slope to increment
// angle formed
$slope_error_new += $m_new;
// Slope error reached limit,
// time to increment y and
// update slope error.
if ($slope_error_new >= 0)
{
$y++;
$slope_error_new -= 2 * ($x2 - $x1);
}
}
}
2700
Chapter 373. Size of The Subarray With Maximum Sum
// Driver Code
$x1 = 3; $y1 = 2; $x2 = 15; $y2 = 5;
bresenham($x1, $y1, $x2, $y2);
// This code is contributed by nitin mittal.
?>
Output :
Source
https://www.geeksforgeeks.org/size-subarray-maximum-sum/
2701
Chapter 374
2702
Chapter 374. Size of array after repeated deletion of LIS
{
// find LIS
lis = findLIS(arr, arr.size());
if (lis.size() < 2)
break;
2703
Chapter 374. Size of array after repeated deletion of LIS
2704
Chapter 374. Size of array after repeated deletion of LIS
Output:
Source
https://www.geeksforgeeks.org/size-array-repeated-deletion-lis/
2705
Chapter 375
Smallest length string with repeated replacement of two distinct adjacent - GeeksforGeeks
Given a string of any combination of three letters ‘a’, ‘b’, and ‘c’, find length of the smallest
string that can be obtained by applying the following operation repeatedly:
Take any two adjacent, distinct characters and replace them with the third.
Examples:
Input : cab
Output : 2
We can select any two adjacent letters,
say 'ca' and transform it into 'b', this
leaves us with string 'bb' of length two.
Input : bcab
Output : 1
Selecting 'bc' and transforming it to 'a'
leaves us with 'aab'. We can then select
'ab' and transform it to 'c', giving 'ac'.
This can further be transformed into 'b',
which is of length one.
A naive way to do this would be to find all possible replacements, and recurse until we find
the minimum string. This would take exponential time.
Lemma: Order of letters does not effect the length or value of minimum string.
2706
Chapter 375. Smallest length string with repeated replacement of two distinct adjacent
Proof By Induction
Base case: Take string ‘ab’ and ‘ba’, they both reduce to ‘c’
Inductive Hypothesis: All strings of length <= k reduce to the same string assuming
the number of occurrences of each letter in each string is the same.
Inductive Step: Take two strings of length k + 1 having same number of occurrences of
each letter. Find a pair of letters that are adjacent
in both strings. Here, two cases arise:
1. We manage to find such a pair of letters. We can then replace these letters with the
third letter, thus getting two strings of length k having same occurrences of each letter,
which by inductive hypothesis reduces to the same string. i.e. We have ‘abcacb’ and
‘accbba’ and reduce ‘ac’ in both strings, we thus get ‘abcbb’ and ‘bcbba’.
2. We cannot find such a pair. This arises when all letters in the string are the same. In
this case, the two strings themselves are the same i.e. ‘ccccccc’ and ‘ccccccc’.
2707
Chapter 375. Smallest length string with repeated replacement of two distinct adjacent
if (b == 0 && c == 0)
return (DP[a][b] = a);
// If only two types of characters are present
if (a == 0)
return (DP[a][b] =
length(a + 1, b - 1, c - 1));
if (b == 0)
return (DP[a][b] =
length(a - 1, b + 1, c - 1));
if (c == 0)
return (DP[a][b] =
length(a - 1, b - 1, c + 1));
// If all types of characters are present.
// Try combining all pairs.
return (DP[a][b] =
min(length(a - 1, b - 1, c + 1),
min(length(a - 1, b + 1, c - 1),
length(a + 1, b - 1, c - 1))));
}
// Returns smallest possible length with given
// operation allowed.
int stringReduction(string str)
{
int n = str.length();
// Counting occurrences of three different
// characters 'a', 'b' and 'c' in str
int count[3] = {0};
for (int i=0; i<n; ++i)
count[str[i]-'a']++;
// Initialize DP[][] entries as -1
for (int i = 0; i <= count[0]; ++i)
for (int j = 0; j < count[1]; ++j)
for (int k = 0; k < count[2]; ++k)
DP[i][j][k] = -1;
return length(count[0], count[1], count[2]);
}
// Driver code
int main()
{
string str = "abcbbaacb";
cout << stringReduction(str);
2708
Chapter 375. Smallest length string with repeated replacement of two distinct adjacent
return 0;
}
Output:
In the worst case, each letter is present in 1/3rd of the whole string. This leads to auxiliary
space = O(N3 ) and time complexity = O(N3 )
Mathematical Approach
We can do better than this using three main principles:
1. If the string cannot be reduced further, then all letters in the string are the same.
2. The length of minimum string is either <= 2 or equal to the length of original string,
or 2 < minimum string length < original string length is never true.
3. If each letter of the string is present an odd amount of times, after one reduction step,
they shall all be present an even amount of times. The converse is also true, that is,
if each letter of the string is present an even amount of times, they shall be present
an odd amount of times after one reduction step.
1. If any two different letters are present, we can select these and reduce string length
further.
2. Proof by contradiction:
Assume we have a reduced string of length less than original string. For example
’bbbbbbb’. Then this string must have originated from a string like ’acbbbbbb’,
’bbacbbbb’ or any other such combination of the same. In this case, we could have
selected ’bc’ instead of ’ac’ and reduced further.
3. From the recursive step above, we increase one letter by one and decrease the other
two by one. So if we had a combination as (odd, odd, odd), then it would become
(odd + 1, odd – 1, odd – 1) or (even, even, even). The reverse is shown in a similar
fashion.
2709
Chapter 375. Smallest length string with repeated replacement of two distinct adjacent
Output:
2710
Chapter 375. Smallest length string with repeated replacement of two distinct adjacent
Source
https://www.geeksforgeeks.org/smallest-length-string-with-repeated-replacement-of-two-distinct-adjacent/
2711
Chapter 376
Smallest number with given sum of digits and sum of square of digits - GeeksforGeeks
Given sum of digits and sum of square of digits . Find the smallest number with given
sum of digits and sum of the square of digits. The number should not contain more than
100 digits. Print -1 if no such number exists or if the number of digits is more than 100.
Examples:
Approach:
Since the smallest number can be of 100 digits, it cannot be stored. Hence the first step to
solve it will be to find the minimum number of digits which can give us the sum of digits
as and sum of the square of digits as . To find the minimum number of digits, we can
use Dynamic Programming. DP[a][b] signifies the minimum number of digits in a number
whose sum of the digits will be and sum of the square of digits will be . If there does
not exist any such number then DP[a][b] will be -1.
Since the number cannot exceed 100 digits, DP array will be of size 101*8101. Iterate for
every digit, and try all possible combination of digits which gives us the sum of digits as
and sum of the square of digits as . Store the minimum number of digits in DP[a][b] using
the below recurrence relation:
2712
Chapter 376. Smallest number with given sum of digits and sum of square of digits
After getting the minimum number of digits, find the digits. To find the digits, check for all
combinations and print those digits which satisfies the condition below:
If the condition above is met by any of i, reduce by i and by i*i and break. Keep on
repeating the above process to find all the digits till is 0 and is 0.
Below is the C++ implementation of above approach:
2713
Chapter 376. Smallest number with given sum of digits and sum of square of digits
// If the combination of digits cannot give sum as a
// and sum of square of digits as b
if (k != -1)
ans = min(ans, k + 1);
}
// Returns the minimum number of digits
return dp[a][b] = ans;
}
// Function to print the digits that gives
// sum as a and sum of square of digits as b
void printSmallestNumber(int a,int b)
{
// initialize the dp array as -1
memset(dp, -1, sizeof(dp));
// base condition
dp[0][0] = 0;
// function call to get the minimum number of digits
int k = minimumNumberOfDigits(a, b);
// When there does not exists any number
if (k == -1 || k > 100)
cout << "-1";
else {
// Printing the digits from the most significant digit
while (a > 0 && b > 0) {
// Trying all combinations
for (int i = 1; i <= 9; i++) {
// checking conditions for minimum digits
if (a >= i && b >= i * i &&
1 + dp[a - i][b - i * i] == dp[a][b]) {
cout << i;
a -= i;
b -= i * i;
break;
}
}
}
}
}
// Driver Code
2714
Chapter 376. Smallest number with given sum of digits and sum of square of digits
int main()
{
int a = 18, b = 162;
// Function call to print the smallest number
printSmallestNumber(a,b);
}
Output:
99
Source
https://www.geeksforgeeks.org/smallest-number-with-given-sum-of-digits-and-sum-of-square-of-digits/
2715
Chapter 377
Naive Approach: Consider all the contiguous subarrays of diiferent sizes and find their
sum. The subarray having the smallest(minimum) sum is the required answer.
Efficient Approach: It is a variation to the problem of finding the largest sum contiguous
subarray based on the idea of Kadane’s algorithm.
Algorithm:
smallestSumSubarr(arr, n)
Initialize min_ending_here = INT_MAX
Initialize min_so_far = INT_MAX
for i = 0 to n-1
if min_ending_here > 0
min_ending_here = arr[i]
2716
Chapter 377. Smallest sum contiguous subarray
else
min_ending_here += arr[i]
min_so_far = min(min_so_far, min_ending_here)
return min_so_far
C++
2717
Chapter 377. Smallest sum contiguous subarray
Java
2718
Chapter 377. Smallest sum contiguous subarray
return min_so_far;
}
// Driver method
public static void main(String[] args)
{
int arr[] = {3, -4, 2, -3, -1, 7, -5};
int n = arr.length;
System.out.print("Smallest sum: "
+ smallestSumSubarr(arr, n));
}
}
// This code is contributed by Anant Agarwal.
Python
2719
Chapter 377. Smallest sum contiguous subarray
return min_so_far
# Driver code
arr = [3, -4, 2, -3, -1, 7, -5]
n = len(arr)
print "Smallest sum: ", smallestSumSubarr(arr, n)
# This code is contributed by Sachin Bisht
C#
2720
Chapter 377. Smallest sum contiguous subarray
PHP
<?php
// PHP implementation to find the
// smallest sum contiguous subarray
// function to find the smallest
// sum contiguous subarray
function smallestSumSubarr($arr, $n)
{
// to store the minimum
// value that is ending
// up to the current index
$min_ending_here = 999999;
// to store the minimum value
// encountered so far
$min_so_far = 999999;
// traverse the array elements
for($i = 0; $i < $n; $i++)
{
// if min_ending_here > 0,
// then it could not possibly
// contribute to the minimum
// sum further
if ($min_ending_here > 0)
2721
Chapter 377. Smallest sum contiguous subarray
$min_ending_here = $arr[$i];
// else add the value arr[i]
// to min_ending_here
else
$min_ending_here += $arr[$i];
// update min_so_far
$min_so_far = min($min_so_far,
$min_ending_here);
}
// required smallest sum
// contiguous subarray value
return $min_so_far;
}
// Driver Code
$arr = array(3, -4, 2, -3, -1, 7, -5);
$n = count($arr) ;
echo "Smallest sum: "
.smallestSumSubarr($arr, $n);
// This code is contributed by Sam007
?>
Output:
Smallest sum: -6
Source
https://www.geeksforgeeks.org/smallest-sum-contiguous-subarray/
2722
Chapter 378
C(n, k) = n! / (n-k)! * k!
= [n * (n-1) *....* 1] / [ ( (n-k) * (n-k-1) * .... * 1) *
( k * (k-1) * .... * 1 ) ]
After simplifying, we get
C(n, k) = [n * (n-1) * .... * (n-k+1)] / [k * (k-1) * .... * 1]
C/C++
2723
Chapter 378. Space and time efficient Binomial Coefficient
// Since C(n, k) = C(n, n-k)
if ( k > n - k )
k = n - k;
// Calculate value of [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
for (int i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
/* Drier program to test above function*/
int main()
{
int n = 8, k = 2;
printf ("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k) );
return 0;
}
Java
2724
Chapter 378. Space and time efficient Binomial Coefficient
Python
C#
2725
Chapter 378. Space and time efficient Binomial Coefficient
PHP
<?php
// Program to calculate C(n ,k)
// Returns value of Binomial
// Coefficient C(n, k)
function binomialCoeff($n,$k)
{
$res = 1;
// Since C(n, k) = C(n, n-k)
if ( $k > $n - $k )
$k = $n - $k;
2726
Chapter 378. Space and time efficient Binomial Coefficient
// Calculate value of
// [n * (n-1) *---* (n-k+1)] /
// [k * (k-1) *----* 1]
for ($i = 0; $i < $k; ++$i)
{
$res *= ($n - $i);
$res /= ($i + 1);
}
return $res;
}
// Driver Code
$n = 8;
$k = 2;
echo " Value of C ($n, $k) is ",
binomialCoeff($n, $k);
// This code is contributed by ajit.
?>
Value of C(8, 2) is 28
Source
https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/
2727
Chapter 379
Input :
Edges : 1 2
1 3
2 4
3 5
Colours : 1 1 2 2 1 [1-based indexing where
index denotes the node]
Output : 2
Explanation : The sub-tree {1-2} and {1-2-3-5}
have color difference of 2. Sub-tree {1-2} has two
1-colour nodes and zero 2-colour nodes. So, color
difference is 2. Sub-tree {1-2-3-5} has three 1-colour
nodes and one 2-colour nodes. So color diff = 2.
Method 1 : The problem can be solved by checking every possible sub-tree from every
node of the tree. This will take exponential time as we will check for sub-trees from every
node.
Method 2 : (Efficient) If we observe, we are solving a portion of the tree several times.
This produces recurring sub-problems. We can use Dynamic Programming approach to
get the minimum color difference in one traversal. To make things simpler, we can have
2728
Chapter 379. Sub-tree with minimum color difference in a 2-coloured tree
color values as 1 and -1. Now, if we have a sub-tree with both colored nodes equal, our sum
of colors will be 0. To get the minimum difference, we should have maximum negative sum
or maximum positive sum.
• Case 1 When we need to have a sub-tree with maximum sum : We take a node if its
value > 0, i.e. sum(parent) += max(0, sum(child))
• Case 2 When we need to have a sub-tree with minimum sum(or max negative sum) :
We take a node if its value < 0, i.e. sum(parent) += min(0, sum(child))
To get the minimum sum, we can interchange the colors of nodes, i.e. -1 becomes 1 and
vice-versa.
Below is the C++ implementation :
2729
Chapter 379. Sub-tree with minimum color difference in a 2-coloured tree
2730
Chapter 379. Sub-tree with minimum color difference in a 2-coloured tree
tree[2].push_back(4);
tree[4].push_back(2);
tree[3].push_back(5);
tree[5].push_back(3);
// Index represent the colour of that node
// There is no Node 0, so we start from
// index 1 to N
int colour[] = { 0, 1, 1, -1, -1, 1 };
// Printing the result
cout << maxDiff(tree, colour, N);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/sub-tree-minimum-color-difference-2-coloured-tree/
2731
Chapter 380
C++
2732
Chapter 380. Subset Sum Problem in O(sum) space
Java
2733
Chapter 380. Subset Sum Problem in O(sum) space
2734
Chapter 380. Subset Sum Problem in O(sum) space
}
// This code is contributed by Sumit Ghosh
Python
Output:
2735
Chapter 380. Subset Sum Problem in O(sum) space
Source
https://www.geeksforgeeks.org/subset-sum-problem-osum-space/
2736
Chapter 381
This problem is a variant of subset sum problem. In subset sum problem we check if given
sum subset exist or not, here we need to find if there exist some subset with sum divisible
by m or not. Seeing input constraint, it looks like typical DP solution will work in O(nm)
time. But in tight time limits in competitive programming, the solution may work. Also
auxiliary space is high for DP table, but here is catch.
If n > m there will always be a subset with sum divisible by m (which is easy to prove
with pigeonhole principle). So we need to handle only cases of n <= m .
For n <= m we create a boolean DP table which will store the status of each value from
0 to m-1 which are possible subset sum (modulo m) which have been encountered so far.
Now we loop through each element of given array arr[], and we add (modulo m) j which have
DP[j] = true and store all the such (j+arr[i])%m possible subset sum in a boolean array
temp, and at the end of iteration over j, we update DP table with temp. Also we add arr[i]
to DP ie.. DP[arr[i]%m] = true.
2737
Chapter 381. Subset with sum divisible by m
In the end if DP[0] is true then it means YES there exist a subset with sum which is divisible
by m, else NO.
C++
2738
Chapter 381. Subset with sum divisible by m
Java
2739
Chapter 381. Subset with sum divisible by m
2740
Chapter 381. Subset with sum divisible by m
Python3
2741
Chapter 381. Subset with sum divisible by m
# This array will keep track of all
# the possible sum (after modulo m)
# which can be made using subsets of arr[]
# initialising boolean array with all false
DP = [False for i in range(m)]
# we'll loop through all the elements of arr[]
for i in range(n):
# anytime we encounter a sum divisible
# by m, we are done
if (DP[0]):
return True
# To store all the new encountered sum (after
# modulo). It is used to make sure that arr[i]
# is added only to those entries for which DP[j]
# was true before current iteration.
temp = [False for i in range(m)]
# For each element of arr[], we loop through
# all elements of DP table from 1 to m and
# we add current element i. e., arr[i] to
# all those elements which are true in DP
# table
for j in range(m):
# if an element is true in DP table
if (DP[j] == True):
if (DP[(j + arr[i]) % m] == False):
# We update it in temp and update
# to DP once loop of j is over
temp[(j + arr[i]) % m] = True
# Updating all the elements of temp
# to DP table since iteration over
# j is over
for j in range(m):
if (temp[j]):
DP[j] = True
# Also since arr[i] is a single element
# subset, arr[i]%m is one of the possible
# sum
DP[arr[i] % m] = True
2742
Chapter 381. Subset with sum divisible by m
return DP[0]
# Driver code
arr = [1, 7]
n = len(arr)
m = 5
print("YES") if(modularSum(arr, n, m)) else print("NO")
# This code is contributed by Anant Agarwal.
C#
2743
Chapter 381. Subset with sum divisible by m
2744
Chapter 381. Subset with sum divisible by m
Console.Write("NO\n");
}
}
//This code is contributed by Anant Agarwal.
Output:
NO
Source
https://www.geeksforgeeks.org/subset-sum-divisible-m/
2745
Chapter 382
Input :[1 2 3 1
4 5 6 1
7 8 9 1
1 1 1 1]
Output: 16
The maximum cost path is:
(3, 3) -> (3, 2) -> (2, 2) -> (1, 1) -> (0, 0).
Cost pathwise is:
1 + 1 + 9 + 5 = 16.
Input: [1 2
3 4]
Output: 4
Optimal Substructure:
The problem is a variation of Min-Cost problem. The path to reach (0, 0) from (n-1, n-1)
must be through the three cells (i, j-1) or (i-1, j) or (i-1, j-1). A top-down recursive function
will be called, for every value of m and n, check if (m+n) is a power of 2 or not. If it is a
power of 2, then move to cell(m-1, n-1) and add the value at a[m][n]. Hence the cost will
be:
2746
Chapter 382. Sudo Placement[1.5] | Wolfish
If it is not a power of 2, then we can move to two of cells (m-1, n) and (m, n-1). So the cost
will be:
2747
Chapter 382. Sudo Placement[1.5] | Wolfish
2748
Chapter 382. Sudo Placement[1.5] | Wolfish
else if (m == 0 && n == 0)
return 0;
// if the state has been visited previously
else if (dp[m][n] != -1)
return dp[m][n];
else {
// i + j
int num = m + n;
// check if it is a power of 2,
// then only move diagonally
if ((num & (num - 1)) == 0)
return dp[m][n] = a[m][n] + maxCost(a, m - 1, n - 1, dp);
// if not a power of 2
// then move side-wise
else
return dp[m][n] = (a[m][n] + max(maxCost(a, m - 1, n, dp),
maxCost(a, m, n - 1, dp)));
}
}
// Function to return the maximum cost
int answer(int a[][size], int n)
{
int dp[size][size];
memset(dp, -1, sizeof dp);
// calling dp function to get the answer
return maxCost(a, n - 1, n - 1, dp);
}
// Driver Code
int main()
{
int a[][size] = { { 1, 2, 3, 1 },
{ 4, 5, 6, 1 },
{ 7, 8, 9, 1 },
{ 1, 1, 1, 1 } };
int n = 4;
// Function calling to get the answer
cout << answer(a, n);
return 0;
}
2749
Chapter 382. Sudo Placement[1.5] | Wolfish
Source
https://www.geeksforgeeks.org/sudo-placement1-5-wolfish/
2750
Chapter 383
We can solve this problem using dynamic programming. We can write summation of all
substrings on basis of digit at which they are ending in that case,
Sum of all substrings = sumofdigit[0] + sumofdigit[1] + sumofdigit[2] … + sumofdigit[n-1]
where n is length of string.
Where sumofdigit[i] stores sum of all substring ending at ith index digit, in above example,
2751
Chapter 383. Sum of all substrings of a string representing a number | Set 1
Now we can get the relation between sumofdigit values and can solve the question iteratively.
Each sumofdigit can be represented in terms of previous value as shown below,
Using above relation we can solve the problem in linear time. In below code a complete
array is taken to store sumofdigit, as each sumofdigit value requires just previous value, we
can solve this problem without allocating complete array also.
C++
2752
Chapter 383. Sum of all substrings of a string representing a number | Set 1
{
int numi = toDigit(num[i]);
// update each sumofdigit from previous value
sumofdigit[i] = (i+1) * numi +
10 * sumofdigit[i-1];
// add current value to the result
res += sumofdigit[i];
}
return res;
}
// Driver code to test above methods
int main()
{
string num = "1234";
cout << sumOfSubstrings(num) << endl;
return 0;
}
Java
2753
Chapter 383. Sum of all substrings of a string representing a number | Set 1
Python3
2754
Chapter 383. Sum of all substrings of a string representing a number | Set 1
C#
2755
Chapter 383. Sum of all substrings of a string representing a number | Set 1
PHP
<?php
// PHP program to print sum of all
// substring of a number represented
// as a string
// Method to covert character
// digit to integer digit
function toDigit($ch)
{
return ($ch - '0');
}
// Returns sum of all
// substring of num
function sumOfSubstrings($num)
{
$n = strlen($num);
// allocate memory equal to
// length of string
$sumofdigit[$n] = 0;
2756
Chapter 383. Sum of all substrings of a string representing a number | Set 1
// initialize first value
// with first digit
$sumofdigit[0] = toDigit($num[0]);
$res = $sumofdigit[0];
// loop over all digits of string
for($i = 1; $i < $n; $i++)
{
$numi = toDigit($num[$i]);
// update each sumofdigit
// from previous value
$sumofdigit[$i] = ($i + 1) * $numi + 10 *
$sumofdigit[$i - 1];
// add current value to the result
$res += $sumofdigit[$i];
}
return $res;
}
// Driver Code
$num = "1234";
echo sumOfSubstrings($num) ;
// This code is contributed by nitin mittal.
?>
Output:
1670
Source
https://www.geeksforgeeks.org/sum-of-all-substrings-of-a-string-representing-a-number/
2757
Chapter 384
Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space) -
GeeksforGeeks
Given a string representing a number, we need to get the sum of all possible sub strings of
this string.
Examples :
Input : s = "6759"
Output : 8421
sum = 6 + 7 + 5 + 9 + 67 + 75 +
59 + 675 + 759 + 6759
= 8421
Input : s = "16"
Output : 23
sum = 1 + 6 + 16 = 23
2758
Chapter 384. Sum of all substrings of a string representing a number | Set 2 (Constant
Extra Space)
1 10 100 1000
6 1 1 1 1
7 2 2 2
5 3 3
9 4
The above table indicates that, when all the sub strings are converted further to the ones,
tens, hundreds etc.. form, each index of the string will have a some fixed occurrence. The
1st index will have 1 occurrence each of ones, tens etc..The 2nd will have 2, 3rd will have 3
and so on.
One more point is that the occurrence of last element will only be restricted to ones. Last
2nd element will be restricted to ones and tens. Last 3rd will be up to hundred and so on.
From the above points lets find out the sum.
Now, to handle the multiplication we will be having a multiplying factor which starts from
1. It’s clear from the example that the multiplying factor(in reverse) is 1, 11, 111, … and so
on. So the multiplication will be based on three factors. number, its index and multiplying
factor.
C++
2759
Chapter 384. Sum of all substrings of a string representing a number | Set 2 (Constant
Extra Space)
Java
2760
Chapter 384. Sum of all substrings of a string representing a number | Set 2 (Constant
Extra Space)
C#
2761
Chapter 384. Sum of all substrings of a string representing a number | Set 2 (Constant
Extra Space)
// Making new multiplying factor as
// explained above.
mf = mf * 10 + 1;
}
return sum;
}
// Driver code to test above methods
public static void Main()
{
string num = "6759";
Console.WriteLine(sumOfSubstrings(num));
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to print sum of
// all substring of a number
// represented as a string
// Returns sum of all
// substring of num
function sumOfSubstrings($num)
{
// Initialize result
$sum = 0;
// Here traversing the array
// in reverse order.Initializing
// loop from last element.
// mf is multiplying factor.
$mf = 1;
for ($i = strlen($num) - 1; $i >= 0; $i--)
{
// Each time sum is added to
// its previous sum. Multiplying
// the three factors as explained above.
// s[i]-'0' is done to convert char to int.
$sum += ($num[$i] - '0') * ($i + 1) * $mf;
2762
Chapter 384. Sum of all substrings of a string representing a number | Set 2 (Constant
Extra Space)
// Making new multiplying
// factor as explained above.
$mf = $mf * 10 + 1;
}
return $sum;
}
// Driver Code
$num = "6759";
echo sumOfSubstrings($num), "\n";
// This code is contributed by m_kit
?>
Output :
8421
Source
https://www.geeksforgeeks.org/sum-substrings-string-representing-number-set-2-constant-extra-space/
2763
Chapter 385
A naive solution is to iterate through all possible subsets, get average of all of them and
then add them one by one, but this will take exponential time and will be infeasible for
bigger arrays.
We can get a pattern by taking an example,
2764
Chapter 385. Sum of average of all subsets
(a1+a3)/2 + (a2+a3)/2 +
(a0+a1+a2)/3 + (a0+a2+a3)/3 + (a0+a1+a3)/3 +
(a1+a2+a3)/3 +
(a0+a1+a2+a3)/4
The coefficient with numerators can be explained as follows, suppose we are iterating over
subsets with K elements then denominator will be K and numerator will be r*S, where
‘r’ denotes number of times a particular array element will be added while iterating over
subsets of same size. By inspection we can see that r will be nCr(N – 1, n – 1) because
after placing one element in summation, we need to choose (n – 1) elements from (N –
1) elements so each element will have a frequency of nCr(N – 1, n – 1) while considering
subsets of same size, as all elements are taking part in summation equal number of times,
this will the frequency of S also and will be the numerator in final expression.
In below code nCr is implemented using dynamic programming method, you can read more
about that here,
C++
2765
Chapter 385. Sum of average of all subsets
}
// method returns sum of average of all subsets
double resultOfAllSubsets(int arr[], int N)
{
double result = 0.0; // Initialize result
// Find sum of elements
int sum = 0;
for (int i = 0; i < N; i++)
sum += arr[i];
// looping once for all subset of same size
for (int n = 1; n <= N; n++)
/* each element occurs nCr(N-1, n-1) times while
considering subset of size n */
result += (double)(sum * (nCr(N - 1, n - 1))) / n;
return result;
}
// Driver code to test above methods
int main()
{
int arr[] = { 2, 3, 5, 7 };
int N = sizeof(arr) / sizeof(int);
cout << resultOfAllSubsets(arr, N) << endl;
return 0;
}
Java
2766
Chapter 385. Sum of average of all subsets
Python3
2767
Chapter 385. Sum of average of all subsets
2768
Chapter 385. Sum of average of all subsets
arr = [2, 3, 5, 7]
N = len(arr)
print(resultOfAllSubsets(arr, N))
# This code is contributed by Anant Agarwal.
C#
2769
Chapter 385. Sum of average of all subsets
int sum = 0;
for (int i = 0; i < N; i++)
sum += arr[i];
// looping once for all subset
// of same size
for (int n = 1; n <= N; n++)
/* each element occurs nCr(N-1, n-1) times while
considering subset of size n */
result += (double)(sum * (nCr(N - 1, n - 1))) / n;
return result;
}
// Driver code to test above methods
public static void Main()
{
int[] arr = { 2, 3, 5, 7 };
int N = arr.Length;
Console.WriteLine(resultOfAllSubsets(arr, N));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to get sum
// of average of all subsets
// Returns value of Binomial
// Coefficient C(n, k)
function nCr($n, $k)
{
$C[$n + 1][$k + 1] = 0;
$i; $j;
// Calculate value of Binomial
// Coefficient in bottom up manner
for ($i = 0; $i <= $n; $i++)
{
for ($j = 0; $j <= min($i, $k); $j++)
{
// Base Cases
if ($j == 0 || $j == $i)
$C[$i][$j] = 1;
2770
Chapter 385. Sum of average of all subsets
// Calculate value using
// previously stored values
else
$C[$i][$j] = $C[$i - 1][$j - 1] +
$C[$i - 1][$j];
}
}
return $C[$n][$k];
}
// method returns sum of
// average of all subsets
function resultOfAllSubsets($arr, $N)
{
// Initialize result
$result = 0.0;
// Find sum of elements
$sum = 0;
for ($i = 0; $i < $N; $i++)
$sum += $arr[$i];
// looping once for all
// subset of same size
for ($n = 1; $n <= $N; $n++)
/* each element occurs nCr(N-1,
n-1) times while considering
subset of size n */
$result += (($sum * (nCr($N - 1,
$n - 1))) / $n);
return $result;
}
// Driver Code
$arr = array( 2, 3, 5, 7 );
$N = sizeof($arr) / sizeof($arr[0]);
echo resultOfAllSubsets($arr, $N) ;
// This code is contributed by nitin mittal.
?>
Output :
63.75
2771
Chapter 385. Sum of average of all subsets
Source
https://www.geeksforgeeks.org/sum-average-subsets/
2772
Chapter 386
Sum of elements of all partitions of number such that no element is less than K - Geeks-
forGeeks
Given an integer N, the task is to find an aggregate sum of all integer partitions of this
number such that each partition does not contain any integer less than K.
Examples:
Input: N = 6 and K = 2
Output: 24
In this case, there are 4 valid partitions.
1) {6}
2) {4, 2}
3) {3, 3}
4) {2, 2, 2}
Therefore, aggregate sum would be
6 + 4 + 2 + 3 + 3 + 2 + 2 + 2 = 24
Input: N = 10 and K = 3
Output: 50
Here, 5 valid partitions are:
1) {10}
2) {7, 3}
3) {6, 4}
4) {5, 5}
5) {3, 3, 4}
Aggregate sum in this case would be
10 + 7 + 3 + 6 + 4 + 5 + 5 + 3 + 3 + 4 = 50
2773
Chapter 386. Sum of elements of all partitions of number such that no element is less
than K
Approach: This problem has a simple recursive solution. First, we need to count the
total number of valid partitions of number N such that each partition contains integers
greater than or equal to K. So we will iteratively apply our recursive solution to find valid
partitions that have the minimum integer K, K+1, K+2, …, N.
Our final answer would be N * no of valid partitions because each valid partition has a
sum equal to N.
Following are some key ideas for designing recursive function to find total number of valid
partitions.
f(N,K):
if N < K
return 0
if N < 2K
return 1
Initialize answer = 1
FOR i from K to N
answer = answer + f(N-i,i)
return answer
C++
2774
Chapter 386. Sum of elements of all partitions of number such that no element is less
than K
2775
Chapter 386. Sum of elements of all partitions of number such that no element is less
than K
Java
// Java implementation of
// above approach
class GFG
{
// Function that returns
// total number of valid
// partitions of integer N
static long countPartitions(int n, int k)
{
// Global declaration of 2D
// dp array which will be
// later used for memoization
long[][] dp = new long[201][201];
// initializing 2D dp array
// with -1 we will use this
// 2D array for memoization
for (int i = 0; i < n + 1; i++)
{
for (int j = 0; j < n + 1; j++)
{
dp[i][j] = -1;
}
}
// if this subproblem is already
// previously calculated, then
// directly return that answer
if (dp[n][k] >= 0)
return dp[n][k];
// if N < K, then no valid
// partition is possible
if (n < k)
return 0;
// if N is between K to 2*K
// then there is only one
// partition and that is
2776
Chapter 386. Sum of elements of all partitions of number such that no element is less
than K
Output:
2777
Chapter 386. Sum of elements of all partitions of number such that no element is less
than K
Source
https://www.geeksforgeeks.org/sum-of-elements-of-all-partitions-of-number-such-that-no-element-is-less-than-k/
2778
Chapter 387
Examples:
Input : n = 3
Output : 15
3C0*3C1 + 3C1*3C2 +3C2*3C3
= 1*3 + 3*3 + 3*1
= 3 + 9 + 3
= 15
Input : n = 4
Output : 56
Method 1: The idea is to find all the binomial coefficients up to nth term and find the
sum of the product of consecutive coefficients.
Below is the implementation of this approach:
C++
2779
Chapter 387. Sum of product of consecutive Binomial Coefficients
PHP
<?php
// PHP Program to find sum
// of product of consecutive
// Binomial Coefficient.
2780
Chapter 387. Sum of product of consecutive Binomial Coefficients
$MAX = 100;
// Find the binomial
// coefficient upto
// nth term
function binomialCoeff($C, $n)
{
$C[0] = 1; // nC0 is 1
for ($i = 1;
$i <= $n; $i++)
{
// Compute next row of
// pascal triangle using
// the previous row
for ($j = min($i, $n);
$j > 0; $j--)
$C[$j] = $C[$j] +
$C[$j - 1];
}
return $C;
}
// Return the sum of the
// product of consecutive
// binomial coefficient.
function sumOfproduct($n)
{
global $MAX;
$sum = 0;
$C = array_fill(0, $MAX, 0);
$C = binomialCoeff($C, $n);
// finding the sum of
// product of consecutive
// coefficient.
for ($i = 0; $i <= $n; $i++)
$sum += $C[$i] * $C[$i + 1];
return $sum;
}
// Driver Code
$n = 3;
echo sumOfproduct($n);
2781
Chapter 387. Sum of product of consecutive Binomial Coefficients
Output
15
Method 2:
We know,
(1 + x)n = n C0 + n C1 *x + n C2 *x2 + …. + n Cn *xn … (1)
(1 + 1/x)n = n C0 + n C1 /x + n C2 /x2 + …. + n Cn /xn … (2)
Multiplying (1) and (2), we get
(1 + x)2n /xn = (n C0 + n C1 *x + n C2 *x2 + …. + n Cn *xn ) * (n C0 + n C1 /x + n C2 /x2 + ….
+ n Cn /xn )
(2n C0 + 2n C1 *x + 2n C2 *x2 + …. + 2n Cn *xn )/xn = (n C0 + n C1 *x + n C2 *x2 + …. + n Cn *xn )
* (n C0 + n C1 /x + n C2 /x2 + …. + n Cn /xn )
Now, find the coefficient of x in LHS,
Observe rth term of expansion in numerator is 2n Cr xr .
To find the coefficient of x in (1 + x)2n /xn , r should be n + 1, because power of x in
denominator will reduce it.
So, coefficient of x in LHS = 2n Cn + 1 or 2n Cn – 1
Now, find the coefficient of x in RHS,
r th term of first expansion of multiplication is n Cr * xr
t th term of second expansion of multiplication is n Ct / xt
So term after multiply will be n Cr * xr * n Ct / xt or
n
Cr * n Ct * x r / x t
Put r = t + 1, we get,
n
Ct+1 * n Ct * x
Observe there will be n such term in the expansion of multiply, so t range from 0 to n – 1.
Therefor, coefficient of x in RHS = n C0 *n C1 + n C1 *n C2 + ….. + n Cn-1 *n Cn
Comparing coefficient of x in LHS and RHS, we can say,
n
C0 *n C1 + n C1 *n C2 + ….. + n Cn-1 *n Cn = 2n Cn – 1
Below is implementation of this approach:
C++
2782
Chapter 387. Sum of product of consecutive Binomial Coefficients
// term
int binomialCoeff(int n, int k)
{
int C[k + 1];
memset(C, 0, sizeof(C));
C[0] = 1; // nC0 is 1
for (int i = 1; i <= n; i++) {
// Compute next row of pascal triangle
// using the previous row
for (int j = min(i, k); j > 0; j--)
C[j] = C[j] + C[j - 1];
}
return C[k];
}
// Return the sum of the product of
// consecutive binomial coefficient.
int sumOfproduct(int n)
{
return binomialCoeff(2 * n, n - 1);
}
// Driven Program
int main()
{
int n = 3;
cout << sumOfproduct(n) << endl;
return 0;
}
Java
2783
Chapter 387. Sum of product of consecutive Binomial Coefficients
int k)
{
int C[] = new int[k + 1];
// memset(C, 0, sizeof(C));
C[0] = 1; // nC0 is 1
for (int i = 1; i <= n; i++)
{
// Compute next row of
// pascal triangle
// using the previous row
for (int j = Math.min(i, k); j > 0; j--)
C[j] = C[j] + C[j - 1];
}
return C[k];
}
// Return the sum of the
// product of consecutive
// binomial coefficient.
static int sumOfproduct(int n)
{
return binomialCoeff(2 * n,
n - 1);
}
// Driver Code
public static void main (String[] args)
{
int n = 3;
System.out.println(sumOfproduct(n));
}
}
// This code is contributed
// by shiv_bhakt.
C#
2784
Chapter 387. Sum of product of consecutive Binomial Coefficients
{
// Find the binomial
// coefficient up to
// nth term
static int binomialCoeff(int n,
int k)
{
int []C = new int[k + 1];
// memset(C, 0, sizeof(C));
C[0] = 1; // nC0 is 1
for (int i = 1; i <= n; i++)
{
// Compute next row of
// pascal triangle
// using the previous row
for (int j = Math.Min(i, k);
j > 0; j--)
C[j] = C[j] + C[j - 1];
}
return C[k];
}
// Return the sum of the
// product of consecutive
// binomial coefficient.
static int sumOfproduct(int n)
{
return binomialCoeff(2 * n,
n - 1);
}
// Driver Code
static public void Main ()
{
int n = 3;
Console.WriteLine(sumOfproduct(n));
}
}
// This code is contributed
// by @ajit.
Output:
2785
Chapter 387. Sum of product of consecutive Binomial Coefficients
15
Source
https://www.geeksforgeeks.org/sum-of-product-of-consecutive-binomial-coefficients/
2786
Chapter 388
Input : n = 2
Output : 4
0.2C0 + 1.2C1 + 2.2C2
= 0*2 + 1*2 + 2*1
= 4
Input : n = 5
Output : 80
Method 1 (Brute Force) : The idea is to iterate a loop i from 0 to n and evaluate i *
n
Ci and add to sum variable.
Below is the implementation of this approach:
C++
2787
Chapter 388. Sum of product of r and rth Binomial Coefficient (r * nCr)
// Return the first n term of binomial coefficient.
void binomialCoeff(int n, int C[])
{
C[0] = 1; // nC0 is 1
for (int i = 1; i <= n; i++) {
// Compute next row of pascal triangle
// using the previous row
for (int j = min(i, n); j > 0; j--)
C[j] = C[j] + C[j - 1];
}
}
// Return summation of r * nCr
int summation(int n)
{
int C[MAX];
memset(C, 0, sizeof(C));
// finding the first n term of binomial
// coefficient
binomialCoeff(n, C);
// Iterate a loop to find the sum.
int sum = 0;
for (int i = 0; i <= n; i++)
sum += (i * C[i]);
return sum;
}
// Driven Program
int main()
{
int n = 2;
cout << summation(n) << endl;
return 0;
}
Java
2788
Chapter 388. Sum of product of r and rth Binomial Coefficient (r * nCr)
{
static int MAX = 100;
// Return the first n term
// of binomial coefficient.
static void binomialCoeff(int n,
int C[])
{
C[0] = 1; // nC0 is 1
for (int i = 1; i <= n; i++)
{
// Compute next row of
// pascal triangle using
// the previous row
for (int j = Math.min(i, n); j > 0; j--)
C[j] = C[j] + C[j - 1];
}
}
// Return summation
// of r * nCr
static int summation(int n)
{
int C[] = new int[MAX];
for(int i = 0; i < MAX; i++)
C[i] = 0;
// finding the first n term
// of binomial coefficient
binomialCoeff(n, C);
// Iterate a loop
// to find the sum.
int sum = 0;
for (int i = 0; i <= n; i++)
sum += (i * C[i]);
return sum;
}
// Driver Code
public static void main(String args[])
{
int n = 2;
System.out.println( summation(n));
2789
Chapter 388. Sum of product of r and rth Binomial Coefficient (r * nCr)
}
}
// This code is contributed by Arnab Kundu
C#
2790
Chapter 388. Sum of product of r and rth Binomial Coefficient (r * nCr)
// Iterate a loop
// to find the sum.
int sum = 0;
for (int i = 0; i <= n; i++)
sum += (i * C[i]);
return sum;
}
// Driver Code
public static void Main()
{
int n = 2;
Console.Write( summation(n));
}
}
// This code is contributed
// by shiv_bhakt
Output:
C++
2791
Chapter 388. Sum of product of r and rth Binomial Coefficient (r * nCr)
// Return summation of r * nCr
int summation(int n)
{
return n << (n - 1);
}
// Driven Program
int main()
{
int n = 2;
cout << summation(n) << endl;
return 0;
}
Java
Python3
2792
Chapter 388. Sum of product of r and rth Binomial Coefficient (r * nCr)
# Coefficient i.e
# summation r * nCr
# Return summation
# of r * nCr
def summation( n):
return n << (n - 1);
# Driver Code
n = 2;
print(summation(n));
# This code is contributed
# by mits
C#
PHP
<?php
// PHP Program to find sum
// of product of r and
2793
Chapter 388. Sum of product of r and rth Binomial Coefficient (r * nCr)
Output:
Source
https://www.geeksforgeeks.org/sum-product-r-rth-binomial-coefficient-r-ncr/
2794
Chapter 389
Input : N = 3
Output : f(1) = 6
f(2) = 11
f(3) = 6
Input : N = 4
Output : f(1) = 10
f(2) = 35
f(3) = 50
f(4) = 24
2795
Chapter 389. Sum of products of all combination taken (1 to n) at a time
Explanation: f(1) = 1 + 2 + 3 + 4 = 10
f(2) = (1*2) + (1*3) + (1*4) +
(2*3) + (2*4) + (3*4)
= 35
f(3) = (1*2*3) + (1*2*4) +(1*3*4) +
(2*3*4)
= 50
f(4) = (1*2*3*4) = 24
A Brute force approach would be to produce all the combinations and then find their
products and sum.
Recursion would do the trick to produce the combinations taken x at a time.
Example : N = 4 taken 3 at a time
C++
2796
Chapter 389. Sum of products of all combination taken (1 to n) at a time
int product = 1;
for (int i = 0; i < r; i++)
product = product * combi[i];
// add the product into sum
sum += product;
return;
}
// recursion to produce different combination
for (int i = depth; i < n; i++) {
combi[index] = a[i];
Combination(a, combi, n, r, i + 1, index + 1);
}
}
// function to print sum of products of
// all combination taken 1-N at a time
void allCombination(int a[], int n) {
for (int i = 1; i <= n; i++) {
// creating temporary array for storing
// combination
int *combi = new int[i];
// call combination with r = i
// for combination taken i at a time
Combination(a, combi, n, i, 0, 0);
// displaying sum
cout << "f(" << i << ") --> " << sum << "\n";
sum = 0;
// free from heap area
free(combi);
}
}
// Driver's code
int main() {
int n = 5;
int *a = new int[n];
// storing numbers from 1-N in array
for (int i = 0; i < n; i++)
a[i] = i + 1;
// calling allCombination
2797
Chapter 389. Sum of products of all combination taken (1 to n) at a time
allCombination(a, n);
return 0;
}
Java
2798
Chapter 389. Sum of products of all combination taken (1 to n) at a time
}
// function to print sum of
// products of all combination
// taken 1-N at a time
static void allCombination(int []a,
int n)
{
for (int i = 1; i <= n; i++)
{
// creating temporary array
// for storing combination
int []combi = new int[i];
// call combination with
// r = i for combination
// taken i at a time
Combination(a, combi, n,
i, 0, 0);
// displaying sum
System.out.print("f(" + i + ") --> " +
sum + "\n");
sum = 0;
}
}
// Driver code
public static void main(String args[])
{
int n = 5;
int []a = new int[n];
// storing numbers
// from 1-N in array
for (int i = 0; i < n; i++)
a[i] = i + 1;
// calling allCombination
allCombination(a, n);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
C#
2799
Chapter 389. Sum of products of all combination taken (1 to n) at a time
2800
Chapter 389. Sum of products of all combination taken (1 to n) at a time
{
for (int i = 1; i <= n; i++)
{
// creating temporary array
// for storing combination
int []combi = new int[i];
// call combination with
// r = i for combination
// taken i at a time
Combination(a, combi, n,
i, 0, 0);
// displaying sum
Console.Write("f(" + i + ") --> " +
sum + "\n");
sum = 0;
}
}
// Driver code
static void Main()
{
int n = 5;
int []a = new int[n];
// storing numbers
// from 1-N in array
for (int i = 0; i < n; i++)
a[i] = i + 1;
// calling allCombination
allCombination(a, n);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output:
f(1) --> 15
f(2) --> 85
f(3) --> 225
f(4) --> 274
2801
Chapter 389. Sum of products of all combination taken (1 to n) at a time
The Time complexity of above code is exponential when the value of N is large.
An Efficient Method is to use the concept of dynamic programming. We don’t have to
find sum of products every time. We can make use of previous results.
Let’s take an example: N = 4
C++
2802
Chapter 389. Sum of products of all combination taken (1 to n) at a time
}
// finding sum of all combination taken 1 to N at a time
void allCombination(int a[], int n) {
int sum = 0;
// sum taken 1 at time is simply sum of 1 - N
for (int i = 1; i <= n; i++)
sum += i;
cout << "f(1) --> " << sum << "\n";
// for sum of products for all combination
for (int i = 1; i < n; i++) {
// finding postfix array
postfix(a, n - i + 1);
// sum of products taken i+1 at a time
sum = 0;
for (int j = 1; j <= n - i; j++) {
sum += (j * a[j]);
}
cout << "f(" << i + 1 << ") --> " << sum << "\n";
// modify the array for overlapping problem
modify(a, n);
}
}
// Driver's Code
int main() {
int n = 5;
int *a = new int[n];
// storing numbers from 1 to N
for (int i = 0; i < n; i++)
a[i] = i + 1;
// calling allCombination
allCombination(a, n);
return 0;
}
Output:
2803
Chapter 389. Sum of products of all combination taken (1 to n) at a time
f(1) --> 15
f(2) --> 85
f(3) --> 225
f(4) --> 274
f(5) --> 120
The Time Complexity of above method is O(n^2) which far more better than the brute
force method.
You can also find the execution time of both the method for large value of N and can see
the difference for yourself.
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/sum-products-combination-taken-1-n-time/
2804
Chapter 390
Super Ugly Number (Number whose prime factors are in given set) - GeeksforGeeks
Super ugly numbers are positive numbers whose all prime factors are in the given prime list.
Given a number n, the task is to find n’th Super Ugly number.
It may be assumed that given set of primes is sorted. Also, first Super Ugly number is 1 by
convention.
Examples:
In our previous post we discussed about Ugly Number. This problem is basically extension
of Ugly Numbers.
2805
Chapter 390. Super Ugly Number (Number whose prime factors are in given set)
A simple solution for this problem is to one by one pick each number starting from 1
and find its all primes factors, if all prime factors lie in the given set of primes that means
number is Super Ugly. Repeat this process until we get n’th Super Ugly Number .
An efficient solution for this problem is similar to Method-2 of Ugly Number. Here is
the algorithm :
2806
Chapter 390. Super Ugly Number (Number whose prime factors are in given set)
// in set
while (ugly.size() != n)
{
// Find minimum element among all current
// multiples of given prime
int next_ugly_no = *min_element(nextMultiple.begin(),
nextMultiple.end());
// insert this super ugly number in set
ugly.insert(next_ugly_no);
// loop to find current minimum is multiple
// of which prime
for (int j=0; j<k; j++)
{
if (next_ugly_no == nextMultiple[j])
{
// increase iterator by one for next multiple
// of current prime
multiple_Of[j]++;
// this loop is similar to find dp[++index[j]]
// it --> dp[++index[j]]
set<int>::iterator it = ugly.begin();
for (int i=1; i<=multiple_Of[j]; i++)
it++;
nextMultiple[j] = primes[j] * (*it);
break;
}
}
}
// n'th super ugly number
set<int>::iterator it = ugly.end();
it--;
return *it;
}
/* Driver program to test above functions */
int main()
{
int primes[] = {2, 5};
int k = sizeof(primes)/sizeof(primes[0]);
int n = 5;
cout << superUgly(n, primes, k);
return 0;
}
2807
Chapter 390. Super Ugly Number (Number whose prime factors are in given set)
Output:
References :
http://stackoverflow.com/questions/34103076/super-ugly-number
Source
https://www.geeksforgeeks.org/super-ugly-number-number-whose-prime-factors-given-set/
2808
Chapter 391
Tabulation vs Memoizatation
1. Tabulation: Bottom Up
2. Memoization: Top Down
Before getting to the definitions of the above two terms consider the below statements:
Both the above versions say the same thing, just the difference lies in the way of conveying
the message and that’s exactly what Bottom Up and Top Down DP do. Version 1 can be
related to as Bottom Up DP and Version-2 can be related as Top Down Dp.
Tabulation Method – Bottom Up Dynamic Programming
As the name itself suggests starting from the bottom and cumulating answers to the top.
Let’s discuss in terms of state transition.
Let’s describe a state for our DP problem to be dp[x] with dp[0] as base state and dp[n] as
our destination state. So, we need to find the value of destination state i.e dp[n].
If we start our transition from our base state i.e dp[0] and follow our state transition relation
to reach our destination state dp[n], we call it Bottom Up approach as it is quite clear that
we started our transition from the bottom base state and reached the top most desired state.
Now, Why do we call it tabulation method?
2809
Chapter 391. Tabulation vs Memoizatation
To know this let’s first write some code to calculate the factorial of a number using bottom
up approach. Once, again as our general procedure to solve a DP we first define a state. In
this case, we define a state as dp[x], where dp[x] is to find the factorial of x.
Now, it is quite obvious that dp[x+1] = dp[x] * (x+1)
// base case
int dp[0] = 1;
for (int i = 1; i< =n; i++)
{
dp[i] = dp[i-1] * i;
}
The above code clearly follows the bottom-up approach as it starts its transition from the
bottom-most base case dp[0] and reaches its destination state dp[n]. Here, we may notice
that the dp table is being populated sequentially and we are directly accessing the calculated
states from the table itself and hence, we call it tabulation method.
Memoization Method – Top Down Dynamic Programming
Once, again let’s describe it in terms of state transition. If we need to find the value for some
state say dp[n] and instead of starting from the base state that i.e dp[0] we ask our answer
from the states that can reach the destination state dp[n] following the state transition
relation, then it is the top-down fashion of DP.
Here, we start our journey from the top most destination state and compute its answer by
taking in count the values of states that can reach the destination state, till we reach the
bottom most base state.
Once again, let’s write the code for the factorial problem in the top-down fashion
// initialized to -1
int dp[MAXN]
// return fact x!
int solve(int x)
{
if (x==0)
return 1;
if (dp[x]!=-1)
return dp[x];
2810
Chapter 391. Tabulation vs Memoizatation
As we can see we are storing the most recent cache up to a limit so that if next time we got
a call from the same state we simply return it from the memory. So, this is why we call it
memoization as we are storing the most recent state values.
In this case the memory layout is linear that’s why it may seem that the memory is being
filled in a sequential manner like the tabulation method, but you may consider any other
top down DP having 2D memory layout like Min Cost Path, here the memory is not filled
in a sequential manner.
Source
https://www.geeksforgeeks.org/tabulation-vs-memoizatation/
2811
Chapter 392
Temple Offerings
Input : 3
1 2 2
Output : 4
All temples must receive at-least one offering.
Now, the second temple is at a higher altitude
compared to the first one. Thus it receives one
extra offering.
The second temple and third temple are at the
same height, so we do not need to modify the
offerings. Offerings given are therefore: 1, 2,
1 giving a total of 4.
Input : 6
1 4 3 6 2 1
Output : 10
We can distribute the offerings in the following
way, 1, 2, 1, 3, 2, 1. The second temple has to
receive more offerings than the first due to its
height being higher. The fourth must receive more
than the fifth, which in turn must receive more
2812
Chapter 392. Temple Offerings
We notice that each temple can either be above, below, or at the same level as the temple
next to it. The offerings required at each temple is equal to the maximum length of the
chain of temples at lower height as shown in the image.
Naive Approach
To follow the given rule, a temple must be offered at least x+1 where x is maximum of
following two.
A naive method of solving this problem would be for each temple, go to the left until altitude
increases, and do the same for the right.
C++
2813
Chapter 392. Temple Offerings
2814
Chapter 392. Temple Offerings
Java
2815
Chapter 392. Temple Offerings
return sum;
}
// Driver code
public static void main (String[] args)
{
int arr1[] = {1, 2, 2};
System.out.println(offeringNumber(3, arr1));
int arr2[] = {1, 4, 3,
6, 2, 1};
System.out.println(offeringNumber(6, arr2));
}
}
// This code is contributed by akt_mit
C#
2816
Chapter 392. Temple Offerings
// Go to right while
// height keeps increasing
for (int j = i + 1; j < n; ++j)
{
if (templeHeight[j] <
templeHeight[j - 1])
++right;
else
break;
}
// This temple should offer
// maximum of two values
// to follow the rule.
sum += Math.Max(right, left) + 1;
}
return sum;
}
// Driver code
static public void Main ()
{
int []arr1 = {1, 2, 2};
Console.WriteLine(offeringNumber(3, arr1));
int []arr2 = {1, 4, 3,
6, 2, 1};
Console.WriteLine(offeringNumber(6, arr2));
}
}
// This code is contributed by aj_36
PHP
<?php
// Program to find minimum total offerings required
// Returns minimum offerings required
function offeringNumber($n, $templeHeight)
{
$sum = 0; // Initialize result
// Go through all templs one by one
for ($i = 0; $i < $n; ++$i)
{
2817
Chapter 392. Temple Offerings
Output:
4
10
2818
Chapter 392. Temple Offerings
each temple and the maximum decreasing chain to the right of each temple. We go through
once from 0 to N setting the value of left for each temple. We then go from N to 0 setting
the value of right for each temple. We then compare the two and pick the maximum for
each temple.
C++
2819
Chapter 392. Temple Offerings
chainSize[i].R = 1;
}
// Computing max of left and right for all
// temples and returing sum.
int sum = 0;
for (int i = 0; i < n; ++i)
sum += max(chainSize[i].L, chainSize[i].R);
return sum;
}
// Driver function
int main()
{
int arr1[3] = {1, 2, 2};
cout << offeringNumber(3, arr1) << "\n";
int arr2[6] = {1, 4, 3, 6, 2, 1};
cout << offeringNumber(6, arr2) << "\n";
return 0;
}
Output:
4
10
Improved By : jit_t
Source
https://www.geeksforgeeks.org/temple-offerings/
2820
Chapter 393
Tetranacci Numbers
For n>=4. They represent the n=4 case of the Fibonacci n-step numbers. The first few
terms for n=0, 1, … are 0, 1, 1, 2, 4, 8, 15, 29, 56, 108, 208, …
Given a number N. The task is to find the N-th tetranacci number.
Examples:
Input: 5
Output: 4
Input: 9
Output: 108
A naive approach is to follow the recurrence for finding the number and use recursion to
solve it.
Below is the implementation of the above approach.
C++
2821
Chapter 393. Tetranacci Numbers
Java
// A simple recursive Java
// program to print the nth
// tetranacci numbers.
class GFG
{
// Function to return the
// N-th tetranacci number
static int printTetraRec(int n)
{
// base cases
if (n == 0)
return 0;
2822
Chapter 393. Tetranacci Numbers
// base cases
if (n == 1 || n == 2)
return 1;
// base cases
if (n == 3)
return 2;
else
return printTetraRec(n – 1) +
printTetraRec(n – 2) +
printTetraRec(n – 3) +
printTetraRec(n – 4);
}
// function to print the
// Nth tetranacci number
static void printTetra(int n)
{
System.out.println(printTetraRec(n) + ” “);
}
// Driver code
public static void main(String[] args)
{
int n = 10;
printTetra(n);
}
}
// This code is contributed by mits
Output:
208
rec(10)
/ / \ \
/ / \ \
2823
Chapter 393. Tetranacci Numbers
In the above partial recursion tree, rec(8), rec(7), rec(6) has been solved twice. On draw-
ing the complete recursion tree, it has been observed that there are many subproblems
which are solved again and again. So this problem has Overlapping Substructure property
and recomputation of same subproblems can be avoided by either using Memoization or
Tabulation.
Below is the implementation of the above approach
// A DP based CPP
// program to print
// the nth tetranacci number
#include <iostream>
using namespace std;
// Function to print the
// N-th tetranacci number
int printTetra(int n)
{
int dp[n + 5];
// base cases
dp[0] = 0;
dp[1] = dp[2] = 1;
dp[3] = 2;
for (int i = 4; i <= n; i++)
dp[i] = dp[i - 1] + dp[i - 2] +
dp[i - 3] + dp[i - 4];
cout << dp[n];
}
// Driver code
int main()
{
int n = 10;
printTetra(n);
return 0;
}
Output:
208
2824
Chapter 393. Tetranacci Numbers
// A space optimized
// based CPP program to
// print the nth tetranacci number
#include <iostream>
using namespace std;
// Function to print the
// N-th tetranacci number
void printTetra(int n)
{
if (n < 0)
return;
// Initialize first
// four numbers to base cases
int first = 0, second = 1;
int third = 1, fourth = 2;
// declare a current variable
int curr;
if (n == 0)
cout << first;
else if (n == 1 || n == 2)
cout << second;
else if (n == 3)
cout << fourth;
else {
// Loop to add previous
// four numbers for
// each number starting
// from 4 and then assign
// first, second, third
// to second, third, fourth and
// curr to fourth respectively
for (int i = 4; i <= n; i++) {
curr = first + second + third + fourth;
first = second;
2825
Chapter 393. Tetranacci Numbers
second = third;
third = fourth;
fourth = curr;
}
cout << curr;
}
}
// Driver code
int main()
{
int n = 10;
printTetra(n);
return 0;
}
Output:
208
Source
https://www.geeksforgeeks.org/tetranacci-numbers/
2826
Chapter 394
1. Empty a Jug
2. Fill a Jug
3. Pour water from one jug to the other until one of the jugs is either empty or full.
There are several ways of solving this problem including BFS and DP. In this article an
arithmetic approach to solve the problem is discussed. The problem can be modeled by
means of Diophantine equation of the form mx + ny = d which is solvable if and only if
gcd(m, n) divides d. Also, the solution x,y for which equation is satisfied can be given using
the Extended Euclid algorithm for GCD.
For example, if we have a jug J1 of 5 litre (n = 5) and another jug J2 of 3 litre (m = 3) and
we have to measure 1 litre of water using them. The associated equation will be 5n + 3m
= 1. First of all this problem can be solved since gcd(3,5) = 1 which divides 1 (See this for
detailed explanation). Using the Extended Euclid algorithm, we get values of n and m for
which the equation is satisfied which are n = 2 and m = -3. These values of n, m also have
some meaning like here n = 2 and m = -3 means that we have to fill J1 twice and empty J2
thrice.
Now to find the minimum no of operations to be performed we have to decide which jug
should be filled first. Depending upon which jug is chosen to be filled and which to be
emptied we have two different solutions and the minimum among them would be our answer.
Solution 1 (Always pour from m litre jug into n litre jug)
2827
Chapter 394. The Two Water Jug Puzzle
Each of steps 1, 2 and 3 are counted as one operation that we perform. Let us say algorithm
1 achieves the task in C1 no of operations.
Solution 2 (Always pour from n litre jug into m litre jug)
(0,0)->(3,0)->(0,3)->(3,3)->(1,5)->(1,0)->(0,1)->(3,1)->(0,4)
(0,0)->(0,5)->(3,2)->(0,2)->(2,0)->(2,5)->(3,4)
2828
Chapter 394. The Two Water Jug Puzzle
if (b==0)
return a;
return gcd(b, a%b);
}
/* fromCap -- Capacity of jug from which
water is poured
toCap -- Capacity of jug to which
water is poured
d -- Amount to be measured */
int pour(int fromCap, int toCap, int d)
{
// Initialize current amount of water
// in source and destination jugs
int from = fromCap;
int to = 0;
// Initialize count of steps required
int step = 1; // Needed to fill "from" Jug
// Break the loop when either of the two
// jugs has d litre water
while (from != d && to != d)
{
// Find the maximum amount that can be
// poured
int temp = min(from, toCap - to);
// Pour "temp" litres from "from" to "to"
to += temp;
from -= temp;
// Increment count of steps
step++;
if (from == d || to == d)
break;
// If first jug becomes empty, fill it
if (from == 0)
{
from = fromCap;
step++;
}
// If second jug becomes full, empty it
if (to == toCap)
{
2829
Chapter 394. The Two Water Jug Puzzle
to = 0;
step++;
}
}
return step;
}
// Returns count of minimum steps needed to
// measure d litre
int minSteps(int m, int n, int d)
{
// To make sure that m is smaller than n
if (m > n)
swap(m, n);
// For d > n we cant measure the water
// using the jugs
if (d > n)
return -1;
// If gcd of n and m does not divide d
// then solution is not possible
if ((d % gcd(n,m)) != 0)
return -1;
// Return minimum two cases:
// a) Water of n litre jug is poured into
// m litre jug
// b) Vice versa of "a"
return min(pour(n,m,d), // n to m
pour(m,n,d)); // m to n
}
// Driver code to test above
int main()
{
int n = 3, m = 5, d = 4;
printf("Minimum number of steps required is %d",
minSteps(m, n, d));
return 0;
}
2830
Chapter 394. The Two Water Jug Puzzle
Source
https://www.geeksforgeeks.org/two-water-jug-puzzle/
2831
Chapter 395
From the above examples, it is obvious that the strategy of dividing the boards into k equal
partitions won’t work for all the cases. We can observe that the problem can be broken
down into: Given an array A of non-negative integers and a positive integer k, we have to
divide A into k of fewer partitions such that the maximum sum of the elements in a partition,
overall partitions is minimized. So for the second example above, possible divisions are:
* One partition: so time is 100.
* Two partitions: (10) & (20, 30, 40), so time is 90. Similarly we can put the first divider
after 20 (=> time 70) or 30 (=> time 60); so this means the minimum time: (100, 90, 70,
60) is 60.
2832
Chapter 395. The painter’s partition problem
A brute force solution is to consider all possible set of contiguous partitions and calculate
the maximum sum partition in each case and return the minimum of all these cases.
1) Optimal Substructure:
We can implement the naive solution using recursion with the following optimal substructure
property:
Assuming that we already have k-1 partitions in place (using k-2 dividers), we now have to
put the k-1 th divider to get k partitions.
How can we do this? We can put the k-1 th divider between the i th and i+1 th element
where i = 1 to n. Please note that putting it before the first element is the same as putting
it after the last element.
The total cost of this arrangement can be calculated as the maximum of the following:
a) The cost of the last partition: sum(Ai..An), where the k-1 th divider is
before element i.
b) The maximum cost of any partition already formed to the left of the k-1 th divider.
Here a) can be found out using a simple helper function to calculate sum
of elements between two indices in the array. How to find out b) ?
We can observe that b) actually is to place the k-2 separators as fairly as
possible, so it is a subproblem of the given problem. Thus we can write the optimal
substructure property as the following recurrence relation:
C++
2833
Chapter 395. The painter’s partition problem
{
int total = 0;
for (int i = from; i <= to; i++)
total += arr[i];
return total;
}
// for n boards and k partitions
int partition(int arr[], int n, int k)
{
// base cases
if (k == 1) // one partition
return sum(arr, 0, n - 1);
if (n == 1) // one board
return arr[0];
int best = INT_MAX;
// find minimum of all possible maximum
// k-1 partitions to the left of arr[i],
// with i elements, put k-1 th divider
// between arr[i-1] & arr[i] to get k-th
// partition
for (int i = 1; i <= n; i++)
best = min(best, max(partition(arr, i, k - 1),
sum(arr, i, n - 1)));
return best;
}
int main()
{
int arr[] = { 10, 20, 60, 50, 30, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
cout << partition(arr, n, k) << endl;
return 0;
}
Java
2834
Chapter 395. The painter’s partition problem
C#
2835
Chapter 395. The painter’s partition problem
2836
Chapter 395. The painter’s partition problem
PHP
<?php
// PHP program for The
// painter's partition problem
// function to calculate sum
// between two indices in array
function sum($arr, $from, $to)
{
$total = 0;
for ($i = $from; $i <= $to; $i++)
$total += $arr[$i];
return $total;
}
// for n boards
// and k partitions
function partition($arr, $n, $k)
{
// base cases
if ($k == 1) // one partition
return sum($arr, 0, $n - 1);
if ($n == 1) // one board
return $arr[0];
$best = PHP_INT_MAX;
// find minimum of all possible
// maximum k-1 partitions to the
// left of arr[i], with i elements,
// put k-1 th divider between
// arr[i-1] & arr[i] to get k-th
// partition
for ($i = 1; $i <= $n; $i++)
$best = min($best,
max(partition($arr, $i, $k - 1),
sum($arr, $i, $n - 1)));
return $best;
}
2837
Chapter 395. The painter’s partition problem
// Driver Code
$arr = array(10, 20, 60,
50, 30, 40);
$n = sizeof($arr);
$k = 3;
echo partition($arr, $n, $k), "\n";
// This code is contributed by ajit
?>
Output :
90
T(4, 3)
/ / \ ..
T(1, 2) T(2, 2) T(3, 2)
/.. /..
T(1, 1) T(1, 1)
We can observe that many subproblems like T(1, 1) in the above problem are being solved
again and again. Because of these two properties of this problem, we can solve it using
dynamic programming, either by top down memoized method or bottom up
tabular method. Following is the bottom up tabular implementation:
C++
2838
Chapter 395. The painter’s partition problem
}
// bottom up tabular dp
int findMax(int arr[], int n, int k)
{
// initialize table
int dp[k + 1][n + 1] = { 0 };
// base cases
// k=1
for (int i = 1; i <= n; i++)
dp[1][i] = sum(arr, 0, i - 1);
// n=1
for (int i = 1; i <= k; i++)
dp[i][1] = arr[0];
// 2 to k partitions
for (int i = 2; i <= k; i++) { // 2 to n boards
for (int j = 2; j <= n; j++) {
// track minimum
int best = INT_MAX;
// i-1 th separator before position arr[p=1..j]
for (int p = 1; p <= j; p++)
best = min(best, max(dp[i - 1][p],
sum(arr, p, j - 1)));
dp[i][j] = best;
}
}
// required
return dp[k][n];
}
// driver function
int main()
{
int arr[] = { 10, 20, 60, 50, 30, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
cout << findMax(arr, n, k) << endl;
return 0;
}
Java
2839
Chapter 395. The painter’s partition problem
2840
Chapter 395. The painter’s partition problem
// required
return dp[k][n];
}
// Driver code
public static void main(String args[])
{
int arr[] = { 10, 20, 60, 50, 30, 40 };
// Calculate size of array.
int n = arr.length;
int k = 3;
System.out.println(findMax(arr, n, k));
}
}
// This code is contributed by Sahil_Bansall
C#
2841
Chapter 395. The painter’s partition problem
PHP
<?php
// A DP based PHP program for
// painter's partition problem
// function to calculate sum
// between two indices in array
function sum($arr, $from, $to)
{
$total = 0;
2842
Chapter 395. The painter’s partition problem
2843
Chapter 395. The painter’s partition problem
$n = sizeof($arr);
$k = 3;
echo findMax($arr, $n, $k) ,"\n";
// This code is contribted by m_kit
?>
Output:
90
Optimizations:
int sum[n+1] = {0};
// sum from 1 to i elements of arr
for (int i = 1; i <= n; i++)
sum[i] = sum[i-1] + arr[i-1];
for (int i = 1; i <= n; i++)
dp[1][i] = sum[i];
and using it to calculate the result as:
best = min(best, max(dp[i-1][p], sum[j] - sum[p]));
2) Though here we consider to divide A into k or fewer partitions, we can observe that
the optimal case always occurs when we divide A into exactly k partitions. So we can use:
2844
Chapter 395. The painter’s partition problem
References:
https://articles.leetcode.com/the-painters-partition-problem/
Asked in: Google, CodeNation
Improved By : vt_m, jit_t
Source
https://www.geeksforgeeks.org/painters-partition-problem/
2845
Chapter 396
In the previous post we discussed a dynamic programming based approach having time
2846
Chapter 396. The painter’s partition problem | Set 2
We also know that the values in this range must be in sorted order. Here our target value
is the maximum sum of a contiguous section in the optimal allocation of boards. Now how
can we apply binary search for this? We can fix the possible low to high range for the target
value and narrow down our search to get the optimal allocation.
We can see that the highest possible value in this range is the sum of all the elementsin the
array and this happens when we allot 1 painter all the sections of the board. The lowest
possible value of this range is the maximum value of the array max, as in this allocation we
can allot max to one painter and divide the other sections such
that the cost of them is less than or equal to max and as close as possible to max. Now if we
consider we use x painters in the above scenarios, it is obvious that as the value in the range
increases, the value of x decreases and vice-versa. From this we can find the target value
when x=k and use a helper function to find x, the minimum number of painters required
when the maximum length of section a painter can paint is given.
C++
2847
Chapter 396. The painter’s partition problem | Set 2
Java
2848
Chapter 396. The painter’s partition problem | Set 2
2849
Chapter 396. The painter’s partition problem | Set 2
C#
2850
Chapter 396. The painter’s partition problem | Set 2
2851
Chapter 396. The painter’s partition problem | Set 2
PHP
<?php
// PHP program for painter's
// partition problem
2852
Chapter 396. The painter’s partition problem | Set 2
// return the maximum
// element from the array
function getMax($arr, $n)
{
$max = PHP_INT_MIN;
for ($i = 0; $i < $n; $i++)
if ($arr[$i] > $max)
$max = $arr[$i];
return $max;
}
// return the sum of the
// elements in the array
function getSum($arr, $n)
{
$total = 0;
for ($i = 0; $i < $n; $i++)
$total += $arr[$i];
return $total;
}
// find minimum required painters
// for given maxlen which is the
// maximum length a painter can paint
function numberOfPainters($arr, $n,
$maxLen)
{
$total = 0; $numPainters = 1;
for ($i = 0; $i < $n; $i++)
{
$total += $arr[$i];
if ($total > $maxLen)
{
// for next count
$total = $arr[$i];
$numPainters++;
}
}
return $numPainters;
}
function partition($arr, $n, $k)
{
2853
Chapter 396. The painter’s partition problem | Set 2
Output :
17
For better understanding, please trace the example given in the program in pen and paper.
2854
Chapter 396. The painter’s partition problem | Set 2
Source
https://www.geeksforgeeks.org/painters-partition-problem-set-2/
2855
Chapter 397
We have infinite number of tiles of sizes 1, 2, …, m. The task is calculate the number of
different stable tower of height n that can be built from these tiles, with a restriction that
you can use at most k tiles of each size in the tower.
Note: Two tower of height n are different if and only if there exists a height h (1 <= h <=
n), such that the towers have tiles of different sizes at height h.
Examples:
Input : n = 3, m = 3, k = 1.
2856
Chapter 397. Tile Stacking Problem
Output : 1
Possible sequences: { 1, 2, 3}.
Hence answer is 1.
Input : n = 3, m = 3, k = 1.
Output : 7
{1, 1, 2}, {1, 1, 3}, {1, 2, 2},
{1, 2, 3}, {1, 3, 3}, {2, 2, 3},
{2, 3, 3}.
We basically need to count number of decreasing sequences of length n using numbers from
1 to m where every number can be used at most k times. We can recursively compute count
for n using count for n-1.
The idea is to use Dynamic Programming. Declare a 2D array dp[][], where each state dp[i][j]
denotes the number of decreasing sequences of length i using numbers from j to m. We need
to take care of the fact that a number can be used a most k times. This can be done by
considering 1 to k occurrences of a number. Hence our recurrence relation becomes:
Also, we can use the fact that for a fixed j we are using the consecutive values of previous
k values of i. Hence, we can maintain a prefix sum array for each state. Now we have got
rid of the k factor for each state.
Below is the C++ implemantation of this approach:
2857
Chapter 397. Tile Stacking Problem
// For each row from 1 to m
for (int i = 1; i < m + 1; i++) {
// For each column from 1 to n.
for (int j = 1; j < n + 1; j++) {
// Initialing dp[i][j] to presum of (i - 1, j).
dp[i][j] = presum[i - 1][j];
if (j > k) {
dp[i][j] -= presum[i - 1][j - k - 1];
}
}
// Calculating presum for each i, 1 <= i <= n.
for (int j = 1; j < n + 1; j++)
presum[i][j] = dp[i][j] + presum[i][j - 1];
}
return dp[m][n];
}
// Driver Program
int main()
{
int n = 3, m = 3, k = 2;
cout << possibleWays(n, m, k) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/tile-stacking-problem/
2858
Chapter 398
Tiling Problem
Input n = 3
Output: 3
Explanation:
We need 3 tiles to tile the board of size 2 x 3.
We can tile the board using following ways
1) Place all 3 tiles vertically.
2) Place first tile vertically and remaining 2 tiles horizontally.
3) Place first 2 tiles horizontally and remaining tiles vertically
Input n = 4
Output: 5
Explanation:
For a 2 x 4 board, there are 5 ways
1) All 4 vertical
2) All 4 horizontal
3) First 2 vertical, remaining 2 horizontal
4) First 2 horizontal, remaining 2 vertical
5) Corner 2 vertical, middle 2 horizontal
2859
Chapter 398. Tiling Problem
Let “count(n)” be the count of ways to place tiles on a “2 x n” grid, we have following two
ways to place first tile.
1) If we place first tile vertically, the problem reduces to “count(n-1)”
2) If we place first tile horizontally, we have to place second tile also horizontally. So the
problem reduces to “count(n-2)”
Therefore, count(n) can be written as below.
count(n) = n if n = 1 or n = 2
count(n) = count(n-1) + count(n-2)
The above recurrence is noting but Fibonacci Number expression. We can find n’th Fi-
bonacci number in O(Log n) time, see below for all method to find n’th Fibonacci Number.
Different methods for n’th Fibonacci Number.
Count the number of ways to tile the floor of size n x m using 1 x m size tiles
This article is contributed by Saurabh Jain. 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/tiling-problem/
2860
Chapter 399
Example 2
Here is one possible way of filling a 3 x 8 board. You have to find all the possible ways to
do so.
Examples :
Input : 2
Output : 3
Input : 8
Output : 153
2861
Chapter 399. Tiling with Dominoes
Input : 12
Output : 2131
Defining Subproblems:
At any point while filling the board, there are three possible states that the last column
can be in:
Finding Reccurences
Note: Even though Bn and Cn are different states, they will be equal for same ‘n’. i.e
Bn = Cn
Hence, we only need to calculate one of them.
Calculating An:
2862
Chapter 399. Tiling with Dominoes
Calculating Bn:
Base Cases:
C++
2863
Chapter 399. Tiling with Dominoes
Java
2864
Chapter 399. Tiling with Dominoes
Python 3
C#
2865
Chapter 399. Tiling with Dominoes
PHP
<?php
// PHP program to find no. of ways
// to fill a 3xn board with 2x1 dominoes.
function countWays($n)
{
$A = array();
$B = array();
$A[0] = 1; $A[1] = 0;
$B[0] = 0; $B[1] = 1;
for ( $i = 2; $i <= $n; $i++)
{
$A[$i] = $A[$i - 2] + 2 *
$B[$i - 1];
$B[$i] = $A[$i - 1] +
$B[$i - 2];
}
return $A[$n];
}
// Driver Code
$n = 8;
echo countWays($n);
// This code is contributed by anuj_67.
?>
Output :
153
2866
Chapter 399. Tiling with Dominoes
Source
https://www.geeksforgeeks.org/tiling-with-dominoes/
2867
Chapter 400
Input : m[][] = { { 1, 2 },
{ 1, 3 } }
Output : 8
Explanation : Decreasing paths are { 1 }, { 1 }, { 2 }, { 3 },
{ 2, 1 }, { 3, 1 }, { 3, 2 }, { 3, 2, 1 }
Input : m[][] = { { 1, 2, 3 },
{ 1, 3, 4 },
{ 1, 5, 6 } }
Output : 41
The idea to solve this problem is to use Dynamic Programming. Declare a dp[][] array,
where dp[i][j] stores the number of decreasing path that can be formed from cell
(i, j). So, we will define a recursive function to evaluate the number of decreasing path
with parameters, say i, j, the row number and column number of the current cell. Make
every possible move from the cell(i,j) and keep a count of the total number of paths. First,
we will check in the function that the number of decreasing paths for input position (i, j) is
already calculated or not. If yes, return the value dp[i][j] else find the number of decreasing
sequence in allowed four directions and return the value. Meanwhile, we will also store the
2868
Chapter 400. Total number of decreasing paths in a matrix
number of decreasing for intermediate cells. Since DP[i][j] stores the number of decreasing
paths for every cell, so the summation of all the cells of DP[][] will answer to count of
decreasing paths in the complete matrix.
Below is the implementation of the above approach:
C++
2869
Chapter 400. Total number of decreasing paths in a matrix
Java
2870
Chapter 400. Total number of decreasing paths in a matrix
2871
Chapter 400. Total number of decreasing paths in a matrix
C#
2872
Chapter 400. Total number of decreasing paths in a matrix
2873
Chapter 400. Total number of decreasing paths in a matrix
{
int[,] dp = new int[n, n];
// Initalising dp[][] to -1.
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
dp[i, j] = -1;
int sum = 0;
// Calculating number of
// decreasing path from each cell.
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
sum += CountDecreasingPathsCell(mat, dp,
n, i, j);
return sum;
}
// Driver code
static public void Main ()
{
int n = 2;
int[,] mat= {{1, 2},
{1, 3}};
// function call that returns the
// count of decreasing paths in a matrix
Console.WriteLine(countDecreasingPathsMatrix(n, mat));
}
}
// This code is contributed by vij.
Output:
2874
Chapter 400. Total number of decreasing paths in a matrix
Source
https://www.geeksforgeeks.org/total-number-of-decreasing-paths-in-a-matrix/
2875
Chapter 401
Input: n = 1
Output: count = 10
Input: n = 2
Output: count = 55
Input: n = 3
Output: count = 220
We strongly recommend you to minimize your browser and try this yourself
first.
One way to look at the problem is, count of numbers is equal to count n digit number ending
with 9 plus count of ending with digit 8 plus count for 7 and so on. How to get count ending
with a particular digit? We can recur for n-1 length and digits smaller than or equal to the
last digit. So below is recursive formula.
Count of n digit numbers = (Count of (n-1) digit numbers Ending with digit 9) +
(Count of (n-1) digit numbers Ending with digit 8) +
2876
Chapter 401. Total number of non-decreasing numbers with n digits
.............................................+
.............................................+
(Count of (n-1) digit numbers Ending with digit 0)
The above recursive solution is going to have many overlapping subproblems. Therefore, we
can use Dynamic Programming to build a table in bottom up manner.
Below is the implementation of above idea :
C++
2877
Chapter 401. Total number of non-decreasing numbers with n digits
// There total nondecreasing numbers of length n
// wiint be dp[0][n] + dp[1][n] ..+ dp[9][n]
for (int i = 0; i < 10; i++)
count += dp[i][n];
return count;
}
// Driver program
int main()
{
int n = 3;
cout << countNonDecreasing(n);
return 0;
}
Java
class NDN
{
static int countNonDecreasing(int n)
{
// dp[i][j] contains total count of non decreasing
// numbers ending with digit i and of length j
int dp[][] = new int[10][n+1];
// Fill table for non decreasing numbers of length 1
// Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
for (int i = 0; i < 10; i++)
dp[i][1] = 1;
// Fill the table in bottom-up manner
for (int digit = 0; digit <= 9; digit++)
{
// Compute total numbers of non decreasing
// numbers of length 'len'
for (int len = 2; len <= n; len++)
{
// sum of all numbers of length of len-1
// in which last digit x is <= 'digit'
for (int x = 0; x <= digit; x++)
dp[digit][len] += dp[x][len-1];
}
}
int count = 0;
2878
Chapter 401. Total number of non-decreasing numbers with n digits
C#
2879
Chapter 401. Total number of non-decreasing numbers with n digits
}
}
int count = 0;
// There total nondecreasing numbers
// of length n wiint be dp[0][n]
// + dp[1][n] ..+ dp[9][n]
for (int i = 0; i < 10; i++)
count += dp[i, n];
return count;
}
// Driver code
public static void Main()
{
int n = 3;
Console.WriteLine(countNonDecreasing(n));
}
}
// This code is contributed by Sam007.
Output:
220
C++
2880
Chapter 401. Total number of non-decreasing numbers with n digits
{
int N = 10;
// Compute value of N*(N+1)/2*(N+2)/3* ....*(N+n-1)/n
long long count = 1;
for (int i=1; i<=n; i++)
{
count *= (N+i-1);
count /= i;
}
return count;
}
// Driver program
int main()
{
int n = 3;
cout << countNonDecreasing(n);
return 0;
}
Java
2881
Chapter 401. Total number of non-decreasing numbers with n digits
int n = 3;
System.out.print(countNonDecreasing(n));
}
}
// This code is contributed by Sam007.
Python3
C#
2882
Chapter 401. Total number of non-decreasing numbers with n digits
{
count *= (N + i - 1);
count /= i;
}
return count;
}
public static void Main()
{
int n = 3;
Console.WriteLine(countNonDecreasing(n));
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to count non-decreasing
// numner with n digits
function countNonDecreasing($n)
{
$N = 10;
// Compute value of N*(N+1)/2*(N+2)/3* ...
// ....*(N+n-1)/n
$count = 1;
for ($i = 1; $i <= $n; $i++)
{
$count *= ($N + $i - 1);
$count /= $i;
}
return $count;
}
// Driver Code
$n = 3;
echo countNonDecreasing($n);
// This code is contributed by Sam007
?>
2883
Chapter 401. Total number of non-decreasing numbers with n digits
Output:
220
For general n digit case, we can apply Mathematical Induction. The count would be equal
to count n-1 digit beginning with 0, i.e., N*(N+1)/2*(N+2)/3* ….*(N+n-1-1)/(n-1). Plus
count of n-1 digit numbers beginning with 1, i.e., (N-1)*(N)/2*(N+1)/3* ….*(N-1+n-1-
1)/(n-1) (Note that N is replaced by N-1) and so on.
Improved By : Sam007
Source
https://www.geeksforgeeks.org/total-number-of-non-decreasing-numbers-with-n-digits/
2884
Chapter 402
Total number of possible Binary Search Trees and Binary Trees with n keys - GeeksforGeeks
Total number of possible Binary Search Trees with n different keys (countBST(n)) = Catalan
number Cn = (2n)!/(n+1)!*n!
For n = 0, 1, 2, 3, … values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862,
…. So are numbers of Binary Search Trees.
Total number of possible Binary Trees with n different keys (countBT(n)) = countBST(n)
* n!
Below is code for finding count of BSTs and Binary Trees with n numbers. The code to find
n’th Catalan number is taken from here.
C++
// See https://www.geeksforgeeks.org/program-nth-catalan-number/
// for reference of below code.
#include <bits/stdc++.h>
using namespace std;
// A function to find factorial of a given number
unsigned long int factorial(unsigned int n)
{
unsigned long int res = 1;
// Calculate value of [1*(2)*---*(n-k+1)] / [k*(k-1)*---*1]
for (int i = 1; i <= n; ++i)
2885
Chapter 402. Total number of possible Binary Search Trees and Binary Trees with n keys
{
res *= i;
}
return res;
}
unsigned long int binomialCoeff(unsigned int n, unsigned int k)
{
unsigned long int res = 1;
// Since C(n, k) = C(n, n-k)
if (k > n - k)
k = n - k;
// Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1]
for (int i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
// A Binomial coefficient based function to find nth catalan
// number in O(n) time
unsigned long int catalan(unsigned int n)
{
// Calculate value of 2nCn
unsigned long int c = binomialCoeff(2*n, n);
// return 2nCn/(n+1)
return c/(n+1);
}
// A function to count number of BST with n nodes
// using catalan
unsigned long int countBST(unsigned int n)
{
// find nth catalan number
unsigned long int count = catalan(n);
// return nth catalan number
return count;
}
2886
Chapter 402. Total number of possible Binary Search Trees and Binary Trees with n keys
Java
// See https://www.geeksforgeeks.org/program-nth-catalan-number/
// for reference of below code.
import java.io.*;
class GFG
{
// A function to find
// factorial of a given number
static int factorial(int n)
{
int res = 1;
// Calculate value of
// [1*(2)*---*(n-k+1)] /
// [k*(k-1)*---*1]
for (int i = 1; i <= n; ++i)
{
res *= i;
2887
Chapter 402. Total number of possible Binary Search Trees and Binary Trees with n keys
}
return res;
}
static int binomialCoeff(int n,
int k)
{
int res = 1;
// Since C(n, k) = C(n, n-k)
if (k > n - k)
k = n - k;
// Calculate value of
// [n*(n-1)*---*(n-k+1)] /
// [k*(k-1)*---*1]
for (int i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
// A Binomial coefficient
// based function to find
// nth catalan number in
// O(n) time
static int catalan( int n)
{
// Calculate value of 2nCn
int c = binomialCoeff(2 * n, n);
// return 2nCn/(n+1)
return c / (n + 1);
}
// A function to count number of
// BST with n nodes using catalan
static int countBST( int n)
{
// find nth catalan number
int count = catalan(n);
2888
Chapter 402. Total number of possible Binary Search Trees and Binary Trees with n keys
C#
// See https://www.geeksforgeeks.org/program-nth-catalan-number/
// for reference of below code.
using System;
class GFG
{
2889
Chapter 402. Total number of possible Binary Search Trees and Binary Trees with n keys
// A function to find
// factorial of a given number
static int factorial(int n)
{
int res = 1;
// Calculate value of
// [1*(2)*---*(n-k+1)] /
// [k*(k-1)*---*1]
for (int i = 1; i <= n; ++i)
{
res *= i;
}
return res;
}
static int binomialCoeff(int n,
int k)
{
int res = 1;
// Since C(n, k) = C(n, n-k)
if (k > n - k)
k = n - k;
// Calculate value of
// [n*(n-1)*---*(n-k+1)] /
// [k*(k-1)*---*1]
for (int i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
// A Binomial coefficient
// based function to find
// nth catalan number in
// O(n) time
static int catalan(int n)
{
// Calculate value
// of 2nCn
2890
Chapter 402. Total number of possible Binary Search Trees and Binary Trees with n keys
2891
Chapter 402. Total number of possible Binary Search Trees and Binary Trees with n keys
PHP
<?php
// See https://www.geeksforgeeks.org/program-nth-catalan-number/
// for reference of below code.
// A function to find factorial
// of a given number
function factorial($n)
{
$res = 1;
// Calculate value of
// [1*(2)*---*(n-k+1)] /
// [k*(k-1)*---*1]
for ($i = 1; $i <= $n; ++$i)
{
$res *= $i;
}
return $res;
}
function binomialCoeff($n, $k)
{
$res = 1;
// Since C(n, k) = C(n, n-k)
if ($k > $n - $k)
$k = $n - $k;
// Calculate value of
// [n*(n-1)*---*(n-k+1)] /
// [k*(k-1)*---*1]
for ($i = 0; $i < $k; ++$i)
{
$res *= ($n - $i);
$res = (int)$res / ($i + 1);
}
return $res;
2892
Chapter 402. Total number of possible Binary Search Trees and Binary Trees with n keys
}
// A Binomial coefficient
// based function to find
// nth catalan number in
// O(n) time
function catalan($n)
{
// Calculate value of 2nCn
$c = binomialCoeff(2 * $n, $n);
// return 2nCn/(n+1)
return (int)$c / ($n + 1);
}
// A function to count
// number of BST with
// n nodes using catalan
function countBST($n)
{
// find nth catalan number
$count = catalan($n);
// return nth
// catalan number
return $count;
}
// A function to count
// number of binary
// trees with n nodes
function countBT($n)
{
// find count of
// BST with n numbers
$count = catalan($n);
// return count * n!
return $count *
factorial($n);
}
// Driver Code
$count1;
$count2;
$n = 5;
// find count of BST and
2893
Chapter 402. Total number of possible Binary Search Trees and Binary Trees with n keys
Output:
Proof of Enumeration
Consider all possible binary search trees with each element at the root. If there are n nodes,
then for each choice of root node, there are n – 1 non-root nodes and these non-root nodes
must be partitioned into those that are less than a chosen root and those that are greater
than the chosen root.
Let’s say node i is chosen to be the root. Then there are i – 1 nodes smaller than i and n
– i nodes bigger than i. For each of these two sets of nodes, there is a certain number of
possible subtrees.
Let t(n) be the total number of BSTs with n nodes. The total number of BSTs with i at the
root is t(i – 1) t(n – i). The two terms are multiplied together because the arrangements in
the left and right subtrees are independent. That is, for each arrangement in the left tree
and for each arrangement in the right tree, you get one BST with i at the root.
Summing over i gives the total number of binary search trees with n nodes.
The base case is t(0) = 1 and t(1) = 1, i.e. there is one empty BST and there is one BST
with one node.
2894
Chapter 402. Total number of possible Binary Search Trees and Binary Trees with n keys
Also, the relationship countBT(n) = countBST(n) * n! holds. As for every possible BST,
there can have n! binary trees where n is the number of nodes in BST.
Improved By : jit_t
Source
https://www.geeksforgeeks.org/total-number-of-possible-binary-search-trees-with-n-keys/
2895
Chapter 403
For example, consider the graph shown in figure on right side. A TSP tour in the graph is
1-2-4-3-1. The cost of the tour is 10+25+30+15 which is 80.
The problem is a famous NP hardproblem. There is no polynomial time know solution for
this problem.
Following are different solutions for the traveling salesman problem.
2896
Chapter 403. Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Naive Solution:
1) Consider city 1 as the starting and ending point.
2) Generate all (n-1)! Permutationsof cities.
3) Calculate cost of every permutation and keep track of minimum cost permutation.
4) Return the permutation with minimum cost.
Time Complexity: Θ(n!)
Dynamic Programming:
Let the given set of vertices be {1, 2, 3, 4,….n}. Let us consider 1 as starting and ending
point of output. For every other vertex i (other than 1), we find the minimum cost path
with 1 as the starting point, i as the ending point and all vertices appearing exactly once.
Let the cost of this path be cost(i), the cost of corresponding Cycle would be cost(i) + dist(i,
1) where dist(i, 1) is the distance from i to 1. Finally, we return the minimum of all [cost(i)
+ dist(i, 1)] values. This looks simple so far. Now the question is how to get cost(i)?
To calculate cost(i) using Dynamic Programming, we need to have some recursive relation
in terms of sub-problems. Let us define a term C(S, i) be the cost of the minimum cost path
visiting each vertex in set S exactly once, starting at 1 and ending at i.
We start with all subsets of size 2 and calculate C(S, i) for all subsets where S is the subset,
then we calculate C(S, i) for all subsets S of size 3 and so on. Note that 1 must be present
in every subset.
For a set of size n, we consider n-2 subsets each of size n-1 such that all subsets don’t have
nth in them.
Using the above recurrence relation, we can write dynamic programming based solution.
There are at most O(n*2n ) subproblems, and each one takes linear time to solve. The total
running time is therefore O(n2 *2n ). The time complexity is much less than O(n!), but still
exponential. Space required is also exponential. So this approach is also infeasible even for
slightly higher number of vertices.
We will soon be discussing approximate algorithms for travelling salesman problem.
Next Article: Traveling Salesman Problem | Set 2
References:
http://www.lsi.upc.edu/~mjserna/docencia/algofib/P07/dynprog.pdf
http://www.cs.berkeley.edu/~vazirani/algorithms/chap6.pdf
Source
https://www.geeksforgeeks.org/travelling-salesman-problem-set-1/
2897
Chapter 404
Traversal of tree with k jumps allowed between nodes of same height - GeeksforGeeks
Consider a tree with n nodes and root. You can jump from one node to any other node on
the same height a maximum of k times on total jumps. Certain nodes of the tree contain a
fruit, find out the maximum number of fruits he can collect.
Example :
Input Tree :
Number of Nodes = 12
Number of jumps allowed : 2
Edges:
1 2
1 3
2 4
2 5
5 9
9 10
9 11
11 12
1 3
3 7
7 6
7 8
Nodes Containing Fruits : 2 4 5 7 8 9 11 12
Output: 7
2898
Chapter 404. Traversal of tree with k jumps allowed between nodes of same height
Explanation:
2899
Chapter 404. Traversal of tree with k jumps allowed between nodes of same height
Approach: The idea is to use DFS to create a Height Adjacency List of the Nodes and to
store the parents. Then use another dfs to compute the maximum no of special nodes that
can be reached using the following dp state:
2900
Chapter 404. Traversal of tree with k jumps allowed between nodes of same height
int Fruit[N];
int Parent[N];
int dp[N][20];
// Function for DFS
void dfs1(vector<int> tree[], int s,
int p, int h)
{
Parent[s] = p;
int i;
H[h].push_back(s);
for (i = 0; i < tree[s].size(); i++) {
int v = tree[s][i];
if (v != p)
dfs1(tree, v, s, h + 1);
}
}
// Function for DFS
int dfs2(vector<int> tree[], int s,
int p, int h, int j)
{
int i;
int ans = 0;
if (dp[s][j] != -1)
return dp[s][j];
// jump
if (j > 0) {
for (i = 0; i < H[h].size(); i++) {
int v = H[h][i];
if (v != s)
ans = max(ans, dfs2(tree, v,
Parent[v], h, j - 1));
}
}
// climb
for (i = 0; i < tree[s].size(); i++) {
int v = tree[s][i];
if (v != p)
ans = max(ans, dfs2(tree, v, s, h + 1, j));
}
if (Fruit[s] == 1)
ans++;
dp[s][j] = ans;
2901
Chapter 404. Traversal of tree with k jumps allowed between nodes of same height
return ans;
}
// Function to calculate and
// return maximum number of fruits
int maxFruit(vector<int> tree[],
int NodesWithFruits[],
int n, int m, int k)
{
// reseting dp table and Fruit array
for (int i = 0; i < N; i++) {
for (int j = 0; j < 20; j++)
dp[i][j] = -1;
Fruit[i] = 0;
}
// This array is used to mark
// which nodes contain Fruits
for (int i = 0; i < m; i++)
Fruit[NodesWithFruits[i]] = 1;
dfs1(tree, 1, 0, 0);
int ans = dfs2(tree, 1, 0, 0, k);
return ans;
}
// Function to add Edge
void addEdge(vector<int> tree[], int u, int v)
{
tree[u].push_back(v);
tree[v].push_back(u);
}
// Driver Code
int main()
{
int n = 12; // Number of nodes
int k = 2; // Number of allowed jumps
vector<int> tree[N];
// Edges
addEdge(tree, 1, 2);
addEdge(tree, 1, 3);
addEdge(tree, 2, 4);
addEdge(tree, 2, 5);
addEdge(tree, 5, 9);
2902
Chapter 404. Traversal of tree with k jumps allowed between nodes of same height
addEdge(tree, 9, 10);
addEdge(tree, 9, 11);
addEdge(tree, 11, 12);
addEdge(tree, 1, 3);
addEdge(tree, 3, 7);
addEdge(tree, 7, 6);
addEdge(tree, 7, 8);
int NodesWithFruits[] = { 2, 4, 5, 7, 8, 9, 11, 12 };
// Number of nodes with fruits
int m = sizeof(NodesWithFruits) / sizeof(NodesWithFruits[0]);
int ans = maxFruit(tree, NodesWithFruits, n, m, k);
cout << ans << endl;
return 0;
}
Output:
Time Complexity : O(n*n*k) (worst case, eg: 2 level tree with the root having n-1 child
nodes)
Source
https://www.geeksforgeeks.org/traversal-tree-ability-jump-nodes-height/
2903
Chapter 405
Ugly Numbers
Input : n = 7
Output : 8
Input : n = 10
Output : 12
Input : n = 15
Output : 24
Input : n = 150
Output : 5832
Method 1 (Simple)
Loop for all positive integers until ugly number count is smaller than n, if an integer is ugly
than increment ugly number count.
To check if a number is ugly, divide the number by greatest divisible powers of 2, 3 and 5,
if the number becomes 1 then it is an ugly number otherwise not.
For example, let us see how to check for 300 is ugly or not. Greatest divisible power of 2 is
4, after dividing 300 by 4 we get 75. Greatest divisible power of 3 is 3, after dividing 75 by
3 we get 25. Greatest divisible power of 5 is 25, after dividing 25 by 25 we get 1. Since we
get 1 finally, 300 is ugly number.
2904
Chapter 405. Ugly Numbers
Implementation:
C/C++
2905
Chapter 405. Ugly Numbers
Java
2906
Chapter 405. Ugly Numbers
}
/* Driver program to test above
functions */
public static void main(String args[])
{
int no = getNthUglyNo(150);
System.out.println("150th ugly "
+ "no. is "+ no);
}
}
// This code has been contributed by
// Amit Khandelwal (Amit Khandelwal 1)
Python3
2907
Chapter 405. Ugly Numbers
no = getNthUglyNo(150)
print("150th ugly no. is ", no)
# This code is contributed by "Sharad_Bhardwaj".
C#
2908
Chapter 405. Ugly Numbers
}
return i;
}
// Driver code
public static void Main()
{
int no = getNthUglyNo(150);
Console.WriteLine("150th ugly"
+ " no. is " + no);
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to find nth ugly number
// This function divides a by
// greatest divisible power of b
function maxDivide($a, $b)
{
while ($a % $b == 0)
$a = $a / $b;
return $a;
}
// Function to check if a
// number is ugly or not
function isUgly($no)
{
$no = maxDivide($no, 2);
$no = maxDivide($no, 3);
$no = maxDivide($no, 5);
return ($no == 1)? 1 : 0;
}
// Function to get the nth
// ugly number
function getNthUglyNo($n)
{
$i = 1;
// ugly number count
2909
Chapter 405. Ugly Numbers
$count = 1;
// Check for all integers
// untill ugly count becomes n
while ($n > $count)
{
$i++;
if (isUgly($i))
$count++;
}
return $i;
}
// Driver Code
$no = getNthUglyNo(150);
echo "150th ugly no. is ". $no;
// This code is contributed by Sam007
?>
Output:
This method is not time efficient as it checks for all integers until ugly number count becomes
n, but space complexity of this method is O(1)
2910
Chapter 405. Ugly Numbers
next_mulitple_of_2 = ugly[i2]*2;
next_mulitple_of_3 = ugly[i3]*3
next_mulitple_of_5 = ugly[i5]*5;
5 Now go in a loop to fill all ugly numbers till 150:
For (i = 1; i < 150; i++ )
{
/* These small steps are not optimized for good
readability. Will optimize them in C program */
next_ugly_no = Min(next_mulitple_of_2,
next_mulitple_of_3,
next_mulitple_of_5);
ugly[i] = next_ugly_no
if (next_ugly_no == next_mulitple_of_2)
{
i2 = i2 + 1;
next_mulitple_of_2 = ugly[i2]*2;
}
if (next_ugly_no == next_mulitple_of_3)
{
i3 = i3 + 1;
next_mulitple_of_3 = ugly[i3]*3;
}
if (next_ugly_no == next_mulitple_of_5)
{
i5 = i5 + 1;
next_mulitple_of_5 = ugly[i5]*5;
}
Example:
Let us see how it works
initialize
ugly[] = | 1 |
i2 = i3 = i5 = 0;
First iteration
ugly[1] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5)
= Min(2, 3, 5)
= 2
ugly[] = | 1 | 2 |
i2 = 1, i3 = i5 = 0 (i2 got incremented )
2911
Chapter 405. Ugly Numbers
Second iteration
ugly[2] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5)
= Min(4, 3, 5)
= 3
ugly[] = | 1 | 2 | 3 |
i2 = 1, i3 = 1, i5 = 0 (i3 got incremented )
Third iteration
ugly[3] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5)
= Min(4, 6, 5)
= 4
ugly[] = | 1 | 2 | 3 | 4 |
i2 = 2, i3 = 1, i5 = 0 (i2 got incremented )
Fourth iteration
ugly[4] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5)
= Min(6, 6, 5)
= 5
ugly[] = | 1 | 2 | 3 | 4 | 5 |
i2 = 2, i3 = 1, i5 = 1 (i5 got incremented )
Fifth iteration
ugly[4] = Min(ugly[i2]*2, ugly[i3]*3, ugly[i5]*5)
= Min(6, 6, 10)
= 6
ugly[] = | 1 | 2 | 3 | 4 | 5 | 6 |
i2 = 3, i3 = 2, i5 = 1 (i2 and i3 got incremented )
C/C++
2912
Chapter 405. Ugly Numbers
{
next_ugly_no = min(next_multiple_of_2,
min(next_multiple_of_3,
next_multiple_of_5));
ugly[i] = next_ugly_no;
if (next_ugly_no == next_multiple_of_2)
{
i2 = i2+1;
next_multiple_of_2 = ugly[i2]*2;
}
if (next_ugly_no == next_multiple_of_3)
{
i3 = i3+1;
next_multiple_of_3 = ugly[i3]*3;
}
if (next_ugly_no == next_multiple_of_5)
{
i5 = i5+1;
next_multiple_of_5 = ugly[i5]*5;
}
} /*End of for loop (i=1; i<n; i++) */
return next_ugly_no;
}
/* Driver program to test above functions */
int main()
{
int n = 150;
cout << getNthUglyNo(n);
return 0;
}
Java
2913
Chapter 405. Ugly Numbers
ugly[0] = 1;
for(int i = 1; i < n; i++)
{
next_ugly_no = Math.min(next_multiple_of_2,
Math.min(next_multiple_of_3,
next_multiple_of_5));
ugly[i] = next_ugly_no;
if (next_ugly_no == next_multiple_of_2)
{
i2 = i2+1;
next_multiple_of_2 = ugly[i2]*2;
}
if (next_ugly_no == next_multiple_of_3)
{
i3 = i3+1;
next_multiple_of_3 = ugly[i3]*3;
}
if (next_ugly_no == next_multiple_of_5)
{
i5 = i5+1;
next_multiple_of_5 = ugly[i5]*5;
}
} /*End of for loop (i=1; i<n; i++) */
return next_ugly_no;
}
/* Driver program to test above functions */
public static void main(String args[])
{
int n = 150;
UglyNumber obj = new UglyNumber();
System.out.println(obj.getNthUglyNo(n));
}
}
// This code has been contributed by Amit Khandelwal (Amit Khandelwal 1)
Python
2914
Chapter 405. Ugly Numbers
# 1 is the first ugly number
ugly[0] = 1
# i2, i3, i5 will indicate indices for 2,3,5 respectively
i2 = i3 =i5 = 0
# set initial multiple value
next_multiple_of_2 = 2
next_multiple_of_3 = 3
next_multiple_of_5 = 5
# start loop to find value from ugly[1] to ugly[n]
for l in range(1, n):
# choose the min value of all available multiples
ugly[l] = min(next_multiple_of_2, next_multiple_of_3, next_multiple_of_5)
# increment the value of index accordingly
if ugly[l] == next_multiple_of_2:
i2 += 1
next_multiple_of_2 = ugly[i2] * 2
if ugly[l] == next_multiple_of_3:
i3 += 1
next_multiple_of_3 = ugly[i3] * 3
if ugly[l] == next_multiple_of_5:
i5 += 1
next_multiple_of_5 = ugly[i5] * 5
# return ugly[n] value
return ugly[-1]
def main():
n = 150
print getNthUglyNo(n)
if __name__ == '__main__':
main()
#This code is contributed by Neelam Yadav
C#
2915
Chapter 405. Ugly Numbers
2916
Chapter 405. Ugly Numbers
// Driver code
public static void Main()
{
int n = 150;
Console.WriteLine(getNthUglyNo(n));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to find
// n'th Ugly number
// Function to get the
// nth ugly number
function getNthUglyNo($n)
{
// To store ugly numbers
$ugly = array_fill(0, $n, 0);
$i2 = 0;
$i3 = 0;
$i5 = 0;
$next_multiple_of_2 = 2;
$next_multiple_of_3 = 3;
$next_multiple_of_5 = 5;
$next_ugly_no = 1;
$ugly[0] = 1;
for ($i = 1; $i < $n; $i++)
{
$next_ugly_no = min($next_multiple_of_2,
min($next_multiple_of_3,
$next_multiple_of_5));
$ugly[$i] = $next_ugly_no;
if ($next_ugly_no ==
$next_multiple_of_2)
{
$i2 = $i2 + 1;
$next_multiple_of_2 = $ugly[$i2] * 2;
}
if ($next_ugly_no ==
$next_multiple_of_3)
{
$i3 = $i3 + 1;
2917
Chapter 405. Ugly Numbers
$next_multiple_of_3 = $ugly[$i3] * 3;
}
if ($next_ugly_no ==
$next_multiple_of_5)
{
$i5 = $i5 + 1;
$next_multiple_of_5 = $ugly[$i5] * 5;
}
} /*End of for loop (i=1; i<n; i++) */
return $next_ugly_no;
}
// Driver code
$n = 150;
echo getNthUglyNo($n);
// This code is contributed by mits
?>
Output :
5832
Source
https://www.geeksforgeeks.org/ugly-numbers/
2918
Chapter 406
Unbounded Knapsack
(Repetition of items allowed)
Input : W = 100
val[] = {1, 30}
wt[] = {1, 50}
Output : 100
There are many ways to fill knapsack.
1) 2 instances of 50 unit weight item.
2) 100 instances of 1 unit weight item.
3) 1 instance of 50 unit weight item and 50
instances of 1 unit weight items.
We get maximum value with option 2.
Input : W = 8
val[] = {10, 40, 50, 70}
wt[] = {1, 3, 4, 5}
Output : 110
We get maximum value with one unit of
weight 5 and one unit of weight 3.
Its an unbounded knapsack problem as we can use 1 or more instances of any resource. A
simple 1D array, say dp[W+1] can be used such that dp[i] stores the maximum value which
2919
Chapter 406. Unbounded Knapsack (Repetition of items allowed)
can achieved using all items and i capacity of knapsack. Note that we use 1D array here
which is different from classical knapsack where we used 2D array. Here number of items
never changes. We always have all items available.
We can recursively compute dp[] using below formula
dp[i] = 0
dp[i] = max(dp[i], dp[i-wt[j]] + val[j]
where j varies from 0
to n-1 such that:
wt[j] <= i
result = d[W]
2920
Chapter 406. Unbounded Knapsack (Repetition of items allowed)
int W = 100;
int val[] = {10, 30, 20};
int wt[] = {5, 10, 15};
int n = sizeof(val)/sizeof(val[0]);
cout << unboundedKnapsack(W, n, val, wt);
return 0;
}
Java
2921
Chapter 406. Unbounded Knapsack (Repetition of items allowed)
Python3
# Python3 program to find maximum
# achievable value with a knapsack
# of weight W and multiple instances allowed.
# Returns the maximum value
# with knapsack of W capacity
def unboundedKnapsack(W, n, val, wt):
# dp[i] is going to store maximum
# value with knapsack capacity i.
dp = [0 for i in range(W + 1)]
ans = 0
# Fill dp[] using above recursive formula
for i in range(W + 1):
for j in range(n):
if (wt[j] <= i):
dp[i] = max(dp[i], dp[i - wt[j]] + val[j])
return dp[W]
# Driver program
W = 100
val = [10, 30, 20]
wt = [5, 10, 15]
n = len(val)
print(unboundedKnapsack(W, n, val, wt))
# This code is contributed by Anant Agarwal.
C#
2922
Chapter 406. Unbounded Knapsack (Repetition of items allowed)
class UboundedKnapsack {
private static int max(int i, int j)
{
return (i > j) ? i : j;
}
// Returns the maximum value
// with knapsack of W capacity
private static int unboundedKnapsack(int W, int n,
int []val, int []wt)
{
// dp[i] is going to store maximum value
// with knapsack capacity i.
int []dp = new int[W + 1];
// Fill dp[] using above recursive formula
for(int i = 0; i <= W; i++){
for(int j = 0; j < n; j++){
if(wt[j] <= i){
dp[i] = Math.Max(dp[i], dp[i - wt[j]] + val[j]);
}
}
}
return dp[W];
}
// Driver program
public static void Main()
{
int W = 100;
int []val = {10, 30, 20};
int []wt = {5, 10, 15};
int n = val.Length;
Console.WriteLine(unboundedKnapsack(W, n, val, wt));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find maximum
// achievable value with a
// knapsack of weight W and
// multiple instances allowed.
2923
Chapter 406. Unbounded Knapsack (Repetition of items allowed)
// Returns the maximum value
// with knapsack of W capacity
function unboundedKnapsack($W, $n,
$val, $wt)
{
// dp[i] is going to store
// maximum value with
// knapsack capacity i.
for($i = 0; $i <= $W; $i++)
$dp[$i] = 0;
$ans = 0;
// Fill dp[] using above
// recursive formula
for ($i = 0; $i <= $W; $i++)
for ($j = 0; $j < $n; $j++)
if ($wt[$j] <= $i)
$dp[$i] = max($dp[$i],
$dp[$i - $wt[$j]] +
$val[$j]);
return $dp[$W];
}
// Driver Code
$W = 100;
$val = array(10, 30, 20);
$wt = array(5, 10, 15);
$n = count($val); //sizeof($val)/sizeof($val[0]);
echo unboundedKnapsack($W, $n,
$val, $wt);
// This code is contributed
// by shiv_bhakt
?>
Output:
300
2924
Chapter 406. Unbounded Knapsack (Repetition of items allowed)
Source
https://www.geeksforgeeks.org/unbounded-knapsack-repetition-items-allowed/
2925
Chapter 407
We have discussed a problem to count the number of unique paths in a Grid when no
obstacle was present in the grid. But here the situation is quite different. While moving
through the grid, we can get some obstacles which we can not jump and that way to reach
the bottom right corner is blocked.
The most efficient solution to this problem can be achieved using dynamic programming.
Like every dynamic problem concept, we will not recompute the subproblems. A temporary
2D matrix will be constructed and value will be stored using the bottom up approach.
• Create a 2D matrix of same size of the given matrix to store the results.
• Traverse through the created array row wise and start filling the values in it.
• If an obstacle is found, set the value to 0.
• For the first row and column, set the value to 1 if obstacle is not found.
2926
Chapter 407. Unique paths in a Grid with Obstacles
• Set the sum of the right and the upper values if obstacle is not present at that corre-
sponding position in the given matirx
• Return the last value of the created 2d matrix
Output:
2927
Chapter 407. Unique paths in a Grid with Obstacles
Source
https://www.geeksforgeeks.org/unique-paths-in-a-grid-with-obstacles/
2928
Chapter 408
Basic Approach : For given value of x, we can calculate F(x) by using simple recursive
function as:
int func(int x)
{
if (x == 0)
return 0;
return (x + func(floor(x/2)));
}
2929
Chapter 408. Value of continuous floor function : F(x) = F(floor(x/2)) + x
In this approach if we have n queries then it will take O(x) for every query element
An Efficient Approach is to use memoization We construct an array which holds the
value of F(x) for each possible value of x. We compute the value if not already computed.
Else we return the value.
C++
2930
Chapter 408. Value of continuous floor function : F(x) = F(floor(x/2)) + x
printFloor(arr, n);
return 0;
}
Java
2931
Chapter 408. Value of continuous floor function : F(x) = F(floor(x/2)) + x
}
}
// This code is contributed by Anant Agarwal.
C#
2932
Chapter 408. Value of continuous floor function : F(x) = F(floor(x/2)) + x
printFloor(arr, n);
}
}
// This code is contributed by nitin mittal
Output:
15 10
Source
https://www.geeksforgeeks.org/value-continuous-floor-function-fx-ffloorx2-x/
2933
Chapter 409
Vertex Cover Problem | Set 2 (Dynamic Programming Solution for Tree) - GeeksforGeeks
A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u,
v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the
set covers all edges of the given graph.
The problem to find minimum size vertex cover of a graph is NP complete. But it can be
solved in polynomial time for trees. In this post a solution for Binary Tree is discussed. The
same solution can be extended for n-ary trees.
For example, consider the following binary tree. The smallest vertex cover is {20, 50, 30}
and size of the vertex cover is 3.
2934
Chapter 409. Vertex Cover Problem | Set 2 (Dynamic Programming Solution for Tree)
The idea is to consider following two possibilities for root and recursively for all nodes down
the root.
1) Root is part of vertex cover: In this case root covers all children edges. We recursively
calculate size of vertex covers for left and right subtrees and add 1 to the result (for root).
2) Root is not part of vertex cover: In this case, both children of root must be included
in vertex cover to cover all root to children edges. We recursively calculate size of vertex
covers of all grandchildren and number of children to the result (for two children of root).
Below is C implementation of above idea.
2935
Chapter 409. Vertex Cover Problem | Set 2 (Dynamic Programming Solution for Tree)
Output:
2936
Chapter 409. Vertex Cover Problem | Set 2 (Dynamic Programming Solution for Tree)
Time complexity of the above naive recursive approach is exponential. It should be noted
that the above function computes the same subproblems again and again. For example,
vCover of node with value 50 is evaluated twice as 50 is grandchild of 10 and child of 20.
Since same suproblems are called again, this problem has Overlapping Subprolems property.
So Vertex Cover problem has both properties (see thisand this) of a dynamic programming
problem. Like other typical Dynamic Programming(DP) problems, re-computations of same
subproblems can be avoided by storing the solutions to subproblems and solving problems
in bottom up manner.
Following is C implementation of Dynamic Programming based solution. In the following
solution, an additional field ‘vc’ is added to tree nodes. The initial value of ‘vc’ is set as
0 for all nodes. The recursive function vCover() calculates ‘vc’ for a node only if it is not
already set.
2937
Chapter 409. Vertex Cover Problem | Set 2 (Dynamic Programming Solution for Tree)
Output:
2938
Chapter 409. Vertex Cover Problem | Set 2 (Dynamic Programming Solution for Tree)
References:
http://courses.csail.mit.edu/6.006/spring11/lectures/lec21.pdf
Exercise:
Extend the above solution for n-ary trees.
This article is contributed by Udit 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/vertex-cover-problem-set-2-dynamic-programming-solution-tree/
2939
Chapter 410
Input: 4 3 2
Output: (0, 0) –> (4, 0) –> (4, 3) –> (0, 3) –> (3, 0) –> (3, 3) –> (4, 2) –>
(0, 2)
Input: 5 2 4
Output: (0, 0) –> (5, 0) –> (5, 2) –> (0, 2) –> (2, 0) –> (2, 2) –> (4, 0)
Approach: An approach using BFS has been discussed in the previous post. In this post
an approach using memoization and recursion has been discussed. At any point, there can
be a total of six possibilities:
Approach: Using Recursion, visit all the six possible moves one by one until one of them
returns True. Since there can be repetitions of same recursive calls, hence every return value
2940
Chapter 410. Water Jug Problem using Memoization
is stored using memoizationto avoid calling the recursive function again and returning the
stored value.
Below is the implementation of the above approach:
2941
Chapter 410. Water Jug Problem using Memoization
Output:
Steps:
0 0
4 0
4 3
0 3
3 0
3 3
4 2
0 2
Source
https://www.geeksforgeeks.org/water-jug-problem-using-memoization/
2942
Chapter 411
Asked in : Google
The idea to solve this problem is using Dynamic Programming. Construct a 2D DP matrix
of m*n size, where m is size of string B and n is size of string A.
dp[i][j] gives the number of ways of transforming string A[0…j] to B[0…i].
• Case 1 : dp[0][j] = 1, since placing B = “” with any substring of A would have only
1 solution which is to delete all characters in A.
2943
Chapter 411. Ways of transforming one string to other by removing 0 or more characters
Source
https://www.geeksforgeeks.org/ways-transforming-one-string-removing-0-characters/
2944
Chapter 412
Ways to arrange Balls such that adjacent balls are of different types - GeeksforGeeks
There are ‘p’ balls of type P, ‘q’ balls of type Q and ‘r’ balls of type R. Using the balls we
want to create a straight line such that no two balls of same type are adjacent.
Examples :
Input : p = 1, q = 1, r = 0
Output : 2
There are only two arrangements PQ and QP
Input : p = 1, q = 1, r = 1
Output : 6
There are only six arrangements PQR, QPR,
QRP, RQP, PRQ and RPQ
Input : p = 2, q = 1, r = 1
Output : 6
There are only six arrangements PQRP, QPRP,
PRQP, RPQP, PRPQ and PQPR
Naive Solution:
The naive solution to this problem is a recursive solution. We recursively call for three cases
1) Last ball to be placed is of type P
2) Last ball to be placed is of type Q
3) Last ball to be placed is of type R
2945
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
C++
2946
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
Java
2947
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
C#
2948
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
class GFG {
// Returns count of arrangements
// where last placed ball is
// 'last'. 'last' is 0 for 'p',
// 1 for 'q' and 2 for 'r'
static int countWays(int p, int q,
int r, int last)
{
// if number of balls of any
// color becomes less than 0
// the number of ways
// arrangements is 0.
if (p < 0 || q < 0 || r < 0)
return 0;
// If last ball required is
// of type P and the number
// of balls of P type is 1
// while number of balls of
// other color is 0 the number
// of ways is 1.
if (p == 1 && q == 0 && r == 0
&& last == 0)
return 1;
// Same case as above for 'q' and 'r'
if (p == 0 && q == 1 && r == 0
&& last == 1)
return 1;
if (p == 0 && q == 0 && r == 1
&& last == 2)
return 1;
// if last ball required is P
// and the number of ways is
// the sum of number of ways
// to form sequence with 'p-1' P
// balls, q Q Balls and r R balls
// ending with Q and R.
if (last == 0)
return countWays(p - 1, q, r, 1) +
countWays(p - 1, q, r, 2);
// Same as above case for 'q' and 'r'
if (last == 1)
return countWays(p, q - 1, r, 0) +
2949
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
countWays(p, q - 1, r, 2);
if (last == 2)
return countWays(p, q, r - 1, 0) +
countWays(p, q, r - 1, 1);
return 0;
}
// Returns count of required arrangements
static int countUtil(int p, int q, int r)
{
// Three cases arise:
// 1. Last required balls is type P
// 2. Last required balls is type Q
// 3. Last required balls is type R
return countWays(p, q, r, 0) +
countWays(p, q, r, 1) +
countWays(p, q, r, 2);
}
// Driver code
public static void Main()
{
int p = 1, q = 1, r = 1;
Console.Write(countUtil(p, q, r));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to count number
// of ways to arrange three
// types of balls such that
// no two balls of same color
// are adjacent to each other
// Returns count of arrangements
// where last placed ball is
// 'last'. 'last' is 0 for 'p',
// 1 for 'q' and 2 for 'r'
function countWays($p, $q,
$r, $last)
2950
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
{
// if number of balls of
// any color becomes less
// than 0 the number of
// ways arrangements is 0.
if ($p < 0 || $q
< 0 || $r < 0)
return 0;
// If last ball required is
// of type P and the number
// of balls of P type is 1
// while number of balls of
// other color is 0 the number
// of ways is 1.
if ($p == 1 && $q == 0 &&
$r == 0 && $last == 0)
return 1;
// Same case as above
// for 'q' and 'r'
if ($p == 0 && $q == 1 &&
$r == 0 && $last == 1)
return 1;
if ($p == 0 && $q == 0 &&
$r == 1 && $last == 2)
return 1;
// if last ball required is P
// and the number of ways is
// the sum of number of ways
// to form sequence with 'p-1' P
// balls, q Q Balls and r R
// balls ending with Q and R.
if ($last == 0)
return countWays($p - 1, $q, $r, 1) +
countWays($p - 1, $q, $r, 2);
// Same as above case
// for 'q' and 'r'
if ($last == 1)
return countWays($p, $q - 1, $r, 0) +
countWays($p, $q - 1, $r, 2);
if ($last == 2)
return countWays($p, $q, $r - 1, 0) +
countWays($p, $q, $r - 1, 1);
2951
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
}
// Returns count of
// required arrangements
function countUtil($p, $q, $r)
{
// Three cases arise:
// Last required balls is type P
// Last required balls is type Q
// Last required balls is type R
return countWays($p, $q, $r, 0) +
countWays($p, $q, $r, 1) +
countWays($p, $q, $r, 2);
}
// Driver Code
$p = 1;
$q = 1;
$r = 1;
echo(countUtil($p, $q, $r));
// This code is contributed by nitin mittal.
?>
Python3
2952
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
2953
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
countWays(p, q, r, 2));
# Driver Code
p = 1;
q = 1;
r = 1;
print(countUtil(p, q, r));
# This code is contributed by mits
Output:
C++
2954
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
// Same case as above for 'q' and 'r'
if (p==0 && q==1 && r==0 && last==1)
return 1;
if (p==0 && q==0 && r==1 && last==2)
return 1;
// If this subproblem is already evaluated
if (dp[p][q][r][last] != -1)
return dp[p][q][r][last];
// if last ball required is P and the number of ways is
// the sum of number of ways to form sequence with 'p-1' P
// balls, q Q Balls and r R balls ending with Q and R.
if (last==0)
dp[p][q][r][last] = countWays(p-1,q,r,1) + countWays(p-1,q,r,2);
// Same as above case for 'q' and 'r'
else if (last==1)
dp[p][q][r][last] = countWays(p,q-1,r,0) + countWays(p,q-1,r,2);
else //(last==2)
dp[p][q][r][last] = countWays(p,q,r-1,0) + countWays(p,q,r-1,1);
return dp[p][q][r][last];
}
// Returns count of required arrangements
int countUtil(int p, int q, int r)
{
// Initialize 'dp' array
memset(dp, -1, sizeof(dp));
// Three cases arise:
return countWays(p, q, r, 0) + // Last required balls is type P
countWays(p, q, r, 1) + // Last required balls is type Q
countWays(p, q, r, 2); // Last required balls is type R
}
// Driver code to test above
int main()
{
int p = 1, q = 1, r = 1;
printf("%d", countUtil(p, q, r));
return 0;
}
Java
2955
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
2956
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
2957
Chapter 412. Ways to arrange Balls such that adjacent balls are of different types
// This code is contributed by Anant Agarwal.
Output:
Source
https://www.geeksforgeeks.org/ways-to-arrange-balls-such-that-adjacent-balls-are-of-different-types/
2958
Chapter 413
countWays(arr, m, N)
Declare and initialize count[N + 1] = {0}
count[0] = 1
for i = 1 to N
2959
Chapter 413. Ways to sum to N using array elements with repetition allowed
for j = 0 to m - 1
if i >= arr[j]
count[i] += count[i - arr[j]]
return count[N]
C++
2960
Chapter 413. Ways to sum to N using array elements with repetition allowed
}
Java
Python3
2961
Chapter 413. Ways to sum to N using array elements with repetition allowed
C#
2962
Chapter 413. Ways to sum to N using array elements with repetition allowed
{
int []count = new int[N+1];
// base case
count[0] = 1;
// count ways for all values up
// to 'N' and store the result
for (int i = 1; i <= N; i++)
for (int j = 0; j < arr.Length; j++)
// if i >= arr[j] then
// accumulate count for value 'i' as
// ways to form value 'i-arr[j]'
if (i >= arr[j])
count[i] += count[i - arr[j]];
// required number of ways
return count[N];
}
// Driver code
public static void Main()
{
int N = 7;
Console.Write("Total number of ways = "
+ countWays(N));
}
}
//This code is contributed by nitin mittal.
Output:
Source
https://www.geeksforgeeks.org/ways-sum-n-using-array-elements-repetition-allowed/
2963
Chapter 414
Input : n = 5
Output : 6
Explanation : All possible six ways are :
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
Input : 4
Output : 4
Explanation : All possible four ways are :
3 + 1
2 + 2
2 + 1 + 1
1 + 1 + 1 + 1
This problem can be solved in the similar fashion as coin change problem, the difference is
only that in this case we should iterate for 1 to n-1 instead of particular values of coin as in
coin-change problem.
C/C++
2964
Chapter 414. Ways to write n as sum of two or more positive integers
Java
2965
Chapter 414. Ways to write n as sum of two or more positive integers
Python
2966
Chapter 414. Ways to write n as sum of two or more positive integers
C#
2967
Chapter 414. Ways to write n as sum of two or more positive integers
{
// table[i] will be storing the number of
// solutions for value i. We need n+1 rows
// as the table is consturcted in bottom up
// manner using the base case (n = 0)
int []table = new int[n+1];
// Initialize all table values as 0
for(int i = 0; i < table.Length; i++)
table[i] = 0;
// Base case (If given value is 0)
table[0] = 1;
// Pick all integer one by one and update the
// table[] values after the index greater
// than or equal to n
for (int i = 1; i < n; i++)
for (int j = i; j <= n; j++)
table[j] += table[j-i];
return table[n];
}
//driver code
public static void Main()
{
int n = 7;
Console.Write(countWays(n));
}
}
//This code is contributed by Anant Agarwal.
Output:
14
Source
https://www.geeksforgeeks.org/ways-to-write-n-as-sum-of-two-or-more-positive-integers/
2968
Chapter 415
1. Start Time
2. Finish Time
3. Profit or Value Associated
Find the maximum profit subset of jobs such that no two jobs in the subset overlap.
Example:
A simple version of this problem is discussed herewhere every job has same profit or value.
The Greedy Strategy for activity selection doesn’t work here as a schedule with more jobs
may have smaller profit or value.
The above problem can be solved using following recursive solution.
2969
Chapter 415. Weighted Job Scheduling
// C++ program for weighted job scheduling using Naive Recursive Method
#include <iostream>
#include <algorithm>
using namespace std;
// A job has start time, finish time and profit.
struct Job
{
int start, finish, profit;
};
// A utility function that is used for sorting events
// according to finish time
bool jobComparataor(Job s1, Job s2)
{
return (s1.finish < s2.finish);
}
// Find the latest job (in sorted array) that doesn't
// conflict with the job[i]. If there is no compatible job,
// then it returns -1.
int latestNonConflict(Job arr[], int i)
{
for (int j=i-1; j>=0; j--)
{
if (arr[j].finish <= arr[i-1].start)
2970
Chapter 415. Weighted Job Scheduling
return j;
}
return -1;
}
// A recursive function that returns the maximum possible
// profit from given array of jobs. The array of jobs must
// be sorted according to finish time.
int findMaxProfitRec(Job arr[], int n)
{
// Base case
if (n == 1) return arr[n-1].profit;
// Find profit when current job is inclueded
int inclProf = arr[n-1].profit;
int i = latestNonConflict(arr, n);
if (i != -1)
inclProf += findMaxProfitRec(arr, i+1);
// Find profit when current job is excluded
int exclProf = findMaxProfitRec(arr, n-1);
return max(inclProf, exclProf);
}
// The main function that returns the maximum possible
// profit from given array of jobs
int findMaxProfit(Job arr[], int n)
{
// Sort jobs according to finish time
sort(arr, arr+n, jobComparataor);
return findMaxProfitRec(arr, n);
}
// Driver program
int main()
{
Job arr[] = {{3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "The optimal profit is " << findMaxProfit(arr, n);
return 0;
}
Output:
2971
Chapter 415. Weighted Job Scheduling
The above solution may contain many overlapping subproblems. For example if lastNon-
Conflicting() always returns previous job, then findMaxProfitRec(arr, n-1) is called twice
and the time complexity becomes O(n*2n ). As another example when lastNonConflicting()
returns previous to previous job, there are two recursive calls, for n-2 and n-1. In this
example case, recursion becomes same as Fibonacci Numbers.
So this problem has both properties of Dynamic Programming, Optimal Substructureand
Overlapping Subproblems.
Like other Dynamic Programming Problems, we can solve this problem by making a table
that stores solution of subproblems.
Below is C++ implementation based on Dynamic Programming.
2972
Chapter 415. Weighted Job Scheduling
Output:
Time Complexity of the above Dynamic Programming Solution is O(n2 ). Note that the
above solution can be optimized to O(nLogn) using Binary Search in latestNonConflict()
instead of linear search. Thanks to Garvit for suggesting this optimization. Please refer
below post for details.
Weighted Job Scheduling in O(n Log n) time
References:
http://courses.cs.washington.edu/courses/cse521/13wi/slides/06dp-sched.pdf
2973
Chapter 415. Weighted Job Scheduling
This article is contributed by Shivam. 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/weighted-job-scheduling/
2974
Chapter 416
1. Start Time
2. Finish Time
3. Profit or Value Associated
Find the maximum profit subset of jobs such that no two jobs in the subset overlap.
Example:
2975
Chapter 416. Weighted Job Scheduling in O(n Log n) time
We have discussed recursive and Dynamic Programming based approaches in the previous
article. The implementations discussed in above post uses linear search to find the previous
non-conflicting job. In this post, Binary Search based solution is discussed. The time
complexity of Binary Search based solution is O(n Log n).
The algorithm is:
To find the profit with inclusion of job[i]. we need to find the latest job that doesn’t conflict
with job[i]. The idea is to use Binary Search to find the latest non-conflicting job.
C/C++
2976
Chapter 416. Weighted Job Scheduling in O(n Log n) time
};
// A utility function that is used for sorting events
// according to finish time
bool myfunction(Job s1, Job s2)
{
return (s1.finish < s2.finish);
}
// A Binary Search based function to find the latest job
// (before current job) that doesn't conflict with current
// job. "index" is index of the current job. This function
// returns -1 if all jobs before index conflict with it.
// The array jobs[] is sorted in increasing order of finish
// time.
int binarySearch(Job jobs[], int index)
{
// Initialize 'lo' and 'hi' for Binary Search
int lo = 0, hi = index - 1;
// Perform binary Search iteratively
while (lo <= hi)
{
int mid = (lo + hi) / 2;
if (jobs[mid].finish <= jobs[index].start)
{
if (jobs[mid + 1].finish <= jobs[index].start)
lo = mid + 1;
else
return mid;
}
else
hi = mid - 1;
}
return -1;
}
// The main function that returns the maximum possible
// profit from given array of jobs
int findMaxProfit(Job arr[], int n)
{
// Sort jobs according to finish time
sort(arr, arr+n, myfunction);
// Create an array to store solutions of subproblems. table[i]
// stores the profit for jobs till arr[i] (including arr[i])
int *table = new int[n];
2977
Chapter 416. Weighted Job Scheduling in O(n Log n) time
table[0] = arr[0].profit;
// Fill entries in table[] using recursive property
for (int i=1; i<n; i++)
{
// Find profit including the current job
int inclProf = arr[i].profit;
int l = binarySearch(arr, i);
if (l != -1)
inclProf += table[l];
// Store maximum of including and excluding
table[i] = max(inclProf, table[i-1]);
}
// Store result and free dynamic memory allocated for table[]
int result = table[n-1];
delete[] table;
return result;
}
// Driver program
int main()
{
Job arr[] = {{3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Optimal profit is " << findMaxProfit(arr, n);
return 0;
}
Python
2978
Chapter 416. Weighted Job Scheduling in O(n Log n) time
2979
Chapter 416. Weighted Job Scheduling in O(n Log n) time
Java
2980
Chapter 416. Weighted Job Scheduling in O(n Log n) time
// Perform binary Search iteratively
while (lo <= hi)
{
int mid = (lo + hi) / 2;
if (jobs[mid].finish <= jobs[index].start)
{
if (jobs[mid + 1].finish <= jobs[index].start)
lo = mid + 1;
else
return mid;
}
else
hi = mid - 1;
}
return -1;
}
// The main function that returns the maximum possible
// profit from given array of jobs
static public int schedule(Job jobs[])
{
// Sort jobs according to finish time
Arrays.sort(jobs, new JobComparator());
// Create an array to store solutions of subproblems.
// table[i] stores the profit for jobs till jobs[i]
// (including jobs[i])
int n = jobs.length;
int table[] = new int[n];
table[0] = jobs[0].profit;
// Fill entries in M[] using recursive property
for (int i=1; i<n; i++)
{
// Find profit including the current job
int inclProf = jobs[i].profit;
int l = binarySearch(jobs, i);
if (l != -1)
inclProf += table[l];
// Store maximum of including and excluding
table[i] = Math.max(inclProf, table[i-1]);
}
return table[n-1];
}
2981
Chapter 416. Weighted Job Scheduling in O(n Log n) time
// Driver method to test above
public static void main(String[] args)
{
Job jobs[] = {new Job(1, 2, 50), new Job(3, 5, 20),
new Job(6, 19, 100), new Job(2, 100, 200)};
System.out.println("Optimal profit is " + schedule(jobs));
}
}
Output:
This article is contributed by Daniel Ray. 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/weighted-job-scheduling-log-n-time/
2982
Chapter 417
Input:
Number of Jobs n = 4
Job Details {Start Time, Finish Time, Profit}
Job 1: {1, 2, 50}
Job 2: {3, 5, 20}
Job 3: {6, 19, 100}
Job 4: {2, 100, 200}
Output:
Job 1: {1, 2, 50}
Job 4: {2, 100, 200}
In previous post, we have discussed about Weighted Job Scheduling problem. We discussed
a DP solution where we basically includes or excludes current job. In this post, another
interesting DP solution is discussed where we also print the Jobs. This problem is a variation
2983
Chapter 417. Weighted Job Scheduling | Set 2 (Using LIS)
of standard Longest Increasing Subsequence (LIS) problem. We need a slight change in the
Dynamic Programming solution of LIS problem.
We first need to sort jobs according to start time. Let job[0..n-1] be the array of jobs after
sorting. We define vector L such that L[i] is itself is a vector that stores Weighted Job
Scheduling of job[0..i] that ends with job[i]. Therefore for an index i, L[i] can be recursively
written as –
L[0] = {job[0]}
L[i] = {MaxSum(L[j])} + job[i] where j < i and job[j].finish <= job[i].start
= job[i], if there is no such j
For example, consider pairs {3, 10, 20}, {1, 2, 50}, {6, 19, 100}, {2, 100, 200}
Therefore,
L[0]: {1, 2, 50}
L[1]: {1, 2, 50} {2, 100, 200}
L[2]: {1, 2, 50} {3, 10, 20}
L[3]: {1, 2, 50} {6, 19, 100}
2984
Chapter 417. Weighted Job Scheduling | Set 2 (Using LIS)
return sum;
}
// The main function that finds the maximum possible
// profit from given array of jobs
void findMaxProfit(vector<Job> &arr)
{
// Sort arr[] by start time.
sort(arr.begin(), arr.end(), compare);
// L[i] stores stores Weighted Job Scheduling of
// job[0..i] that ends with job[i]
vector<vector<Job>> L(arr.size());
// L[0] is equal to arr[0]
L[0].push_back(arr[0]);
// start from index 1
for (int i = 1; i < arr.size(); i++)
{
// for every j less than i
for (int j = 0; j < i; j++)
{
// L[i] = {MaxSum(L[j])} + arr[i] where j < i
// and arr[j].finish <= arr[i].start
if ((arr[j].finish <= arr[i].start) &&
(findSum(L[j]) > findSum(L[i])))
L[i] = L[j];
}
L[i].push_back(arr[i]);
}
vector<Job> maxChain;
// find one with max profit
for (int i = 0; i < L.size(); i++)
if (findSum(L[i]) > findSum(maxChain))
maxChain = L[i];
for (int i = 0; i < maxChain.size(); i++)
cout << "(" << maxChain[i].start << ", " <<
maxChain[i].finish << ", "
<< maxChain[i].profit << ") ";
}
// comparator function for sort function
int compare(Job x, Job y)
{
2985
Chapter 417. Weighted Job Scheduling | Set 2 (Using LIS)
Output:
Source
https://www.geeksforgeeks.org/weighted-job-scheduling-set-2-using-lis/
2986
Chapter 418
Weird Number
Input: 40
Output: The number is not weird
1+4+5+10+20=40, hence it is not weird.
Input: 70
Output: The number is Weird
The smallest weird number is 70. Its proper divisors are 1, 2, 5, 7, 10, 14, and
35; these sum to 74, but no subset of these sums to 70.
The number 12, for example, is abundant but not weird, because the proper
divisors of 12 are 1, 2, 3, 4, and 6, which sum to 16; but 2+4+6 = 12. The
first few weird numbers are 70, 836, 4030, 5830, 7192, 7912, 9272, 10430, 10570,
10792, 10990, 11410, 11690, 12110, 12530, 12670, 13370, 13510, ..
Approach: Check if the number is abundant or not. The approach has been discussed here.
Once the checking has been done check if the number is semiperfect or not. The approach
for checking semiperfects numbers has been discussed here.
Below is the implementation of the above approach:
C++
2987
Chapter 418. Weird Number
2988
Chapter 418. Weird Number
return true;
else
return false;
}
// Function to check if the
// number is semi-perfecr or not
bool checkSemiPerfect(int n)
{
vector<int> v;
// find the divisors
v = factors(n);
// sorting the vector
sort(v.begin(), v.end());
int r = v.size();
// subset to check if no is semiperfect
bool subset[r + 1][n + 1];
// initialising 1st column to true
for (int i = 0; i <= r; i++)
subset[i][0] = true;
// initialing 1st row except zero position to 0
for (int i = 1; i <= n; i++)
subset[0][i] = false;
// loop to find whther the number is semiperfect
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= n; j++) {
// calculation to check if the
// number can be made by summation of diviors
if (j < v[i - 1])
subset[i][j] = subset[i - 1][j];
else {
subset[i][j] = subset[i - 1][j] ||
subset[i - 1][j - v[i - 1]];
}
}
}
// if not possible to make the
// number by any combination of divisors
if ((subset[r][n]) == 0)
2989
Chapter 418. Weird Number
return false;
else
return true;
}
// Function to check for
// weird or not
bool checkweird(int n)
{
if (checkAbundant(n) == true &&
checkSemiPerfect(n) == false)
return true;
else
return false;
}
// Driver Code
int main()
{
int n = 70;
if (checkweird(n))
cout << "Weird Number";
else
cout << "Not Weird Number";
return 0;
}
Java
2990
Chapter 418. Weird Number
2991
Chapter 418. Weird Number
// Function to check if the
// number is semi-perfecr or not
static boolean checkSemiPerfect(int n)
{
ArrayList<Integer> v;
// find the divisors
v = factors(n);
// sorting the ArrayList
Collections.sort(v);
int r = v.size();
// subset to check if
// no is semiperfect
boolean subset[][] = new boolean[r + 1][n + 1];
// initialising 1st
// column to true
for (int i = 0; i <= r; i++)
subset[i][0] = true;
// initialing 1st row except
// zero position to 0
for (int i = 1; i <= n; i++)
subset[0][i] = false;
// loop to find whther
// the number is semiperfect
for (int i = 1; i <= r; i++)
{
for (int j = 1; j <= n; j++)
{
// calculation to check
// if the number can be
// made by summation of
// diviors
if (j < v.get(i - 1))
subset[i][j] = subset[i - 1][j];
else {
subset[i][j] = subset[i - 1][j] ||
subset[i - 1][j -
v.get(i - 1)];
}
}
2992
Chapter 418. Weird Number
}
// if not possible to make
// the number by any
// combination of divisors
if ((subset[r][n]) == false)
return false;
else
return true;
}
// Function to check
// for weird or not
static boolean checkweird(int n)
{
if (checkAbundant(n) == true &&
checkSemiPerfect(n) == false)
return true;
else
return false;
}
// Driver Code
public static void main(String args[])
{
int n = 70;
if (checkweird(n))
System.out.println("Weird Number");
else
System.out.println("Not Weird Number");
}
}
// This code is contributed
// by Arnab Kundu
Output:
Weird Number
2993
Chapter 418. Weird Number
Source
https://www.geeksforgeeks.org/weird-number/
2994
Chapter 419
Examples:
2995
Chapter 419. WildCard pattern matching having three symbols ( * , + , ? )
2996
Chapter 419. WildCard pattern matching having three symbols ( * , + , ? )
2997
Chapter 419. WildCard pattern matching having three symbols ( * , + , ? )
2998
Chapter 419. WildCard pattern matching having three symbols ( * , + , ? )
}
return lookup[m][n].value;
}
// Driver code
int main()
{
string str = "baaabaaa";
string pattern = "*****+ba***+";
if (strmatch(str, pattern, str.length(),
pattern.length()))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/wildcard-pattern-matching-three-symbols/
2999
Chapter 420
Text = "baaabab",
Pattern = “*****ba*****ab", output : true
Pattern = "baaa?ab", output : true
Pattern = "ba*a?", output : true
Pattern = "a*ab", output : false
3000
Chapter 420. Wildcard Pattern Matching
Each occurrence of ‘?’ character in wildcard pattern can be replaced with any other character
and each occurrence of ‘*’ with a sequence of characters such that the wildcard pattern
becomes identical to the input string after replacement.
Let’s consider any character in the pattern.
Case 1: The character is ‘*’
Here two cases arise
1. We can ignore ‘*’ character and move to next character in the Pattern.
2. ‘*’ character matches with one or more characters in Text. Here we will move to next
character in the string.
3001
Chapter 420. Wildcard Pattern Matching
// pattern is null
T[i][0] = false;
// text is null
T[0][j] = T[0][j - 1] if pattern[j – 1] is '*'
DP relation :
C++
3002
Chapter 420. Wildcard Pattern Matching
#include <bits/stdc++.h>
using namespace std;
// Function that matches input str with
// given wildcard pattern
bool strmatch(char str[], char pattern[],
int n, int m)
{
// empty pattern can only match with
// empty string
if (m == 0)
return (n == 0);
// lookup table for storing results of
// subproblems
bool lookup[n + 1][m + 1];
// initailze lookup table to false
memset(lookup, false, sizeof(lookup));
// empty pattern can match with empty string
lookup[0][0] = true;
// Only '*' can match with empty string
for (int j = 1; j <= m; j++)
if (pattern[j - 1] == '*')
lookup[0][j] = lookup[0][j - 1];
// fill the table in bottom-up fashion
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
// Two cases if we see a '*'
// a) We ignore ‘*’ character and move
// to next character in the pattern,
// i.e., ‘*’ indicates an empty sequence.
// b) '*' character matches with ith
// character in input
if (pattern[j - 1] == '*')
lookup[i][j] = lookup[i][j - 1] ||
lookup[i - 1][j];
// Current characters are considered as
// matching in two cases
// (a) current character of pattern is '?'
// (b) characters actually match
else if (pattern[j - 1] == '?' ||
3003
Chapter 420. Wildcard Pattern Matching
Java
3004
Chapter 420. Wildcard Pattern Matching
3005
Chapter 420. Wildcard Pattern Matching
Output :
Yes
Time complexity of above solution is O(m x n). Auxiliary space used is also O(m x n).
Further Improvements:
We can improve space complexity by making use of the fact that we only uses the result
from last row.
One more improvement is yo merge consecutive ‘*’ in the pattern to single ‘*’ as they mean
3006
Chapter 420. Wildcard Pattern Matching
the same thing. For example for pattern “*****ba*****ab”, if we merge consecutive stars,
the resultant string will be “*ba*ab”. So, value of m is reduced from 14 to 6.
Source
https://www.geeksforgeeks.org/wildcard-pattern-matching/
3007
Chapter 421
Input format: Input will consists of array of integers where each array element represents length
Output format: Output consists of a series of integers where two consecutive integers represent
starting word and ending word of each line.
3008
Chapter 421. Word Wrap problem ( Space optimized solution )
Approach: We have discussed a Dynamic Programming based solution of word wrap prob-
lem. The solution discussed used O(n^2) auxiliary space. The auxiliary space used can be
reduced to O(n). The idea is to use two 1-D arrays dp[] and ans[], where dp[i] represents
minimum cost of the line in which arr[i] is the first word and ans[i] represents index of last
word present in line in which word arr[i] is the first word. Let k represents limit on number
of characters in each line. Suppose for any line l the first word in that line is at index i in
arr[]. The minimum cost of that line is stored in dp[i]. The last word in that line is at index
j in arr[], where j can vary from i to n. Iterate over all values of j and keep track of number
of characters added so far in line l. If number of characters are less than k then find cost of
current line with these number of characters. Compare this cost with minimum cost find so
far for this line in dp[i] and update dp[i] and ans[i] accordingly. Repeat above procedure for
each value of i, 1 <= i <= n. The starting and ending words of each line will be at index i
and index ans[i], where next value of i for line l+1 is ans[i] + 1.
Implementation:
C++
3009
Chapter 421. Word Wrap problem ( Space optimized solution )
int dp[n];
// Array in which ans[i] store index
// of last word in line starting with
// word arr[i].
int ans[n];
// If only one word is present then
// only one line is required. Cost
// of last line is zero. Hence cost
// of this line is zero. Ending point
// is also n-1 as single word is
// present.
dp[n - 1] = 0;
ans[n - 1] = n - 1;
// Make each word first word of line
// by iterating over each index in arr.
for (i = n - 2; i >= 0; i--) {
currlen = -1;
dp[i] = INT_MAX;
// Keep on adding words in current
// line by iterating from starting
// word upto last word in arr.
for (j = i; j < n; j++) {
// Update number of characters
// in current line. arr[j] is
// number of characters in
// current word and 1
// represents space character
// between two words.
currlen += (arr[j] + 1);
// If limit of characters
// is violated then no more
// words can be added to
// current line.
if (currlen > k)
break;
// If current word that is
// added to line is last
// word of arr then current
// line is last line. Cost of
// last line is 0. Else cost
// is square of extra spaces
3010
Chapter 421. Word Wrap problem ( Space optimized solution )
Java
3011
Chapter 421. Word Wrap problem ( Space optimized solution )
// optimized solution of
// Word Wrap problem.
static void solveWordWrap(int arr[],
int n, int k)
{
int i, j;
// Variable to store
// number of characters
// in given line.
int currlen;
// Variable to store
// possible minimum
// cost of line.
int cost;
// DP table in which
// dp[i] represents
// cost of line starting
// with word arr[i].
int dp[] = new int[n];
// Array in which ans[i]
// store index of last
// word in line starting
// with word arr[i].
int ans[] = new int[n];
// If only one word is present
// then only one line is required.
// Cost of last line is zero.
// Hence cost of this line is zero.
// Ending point is also n-1 as
// single word is present.
dp[n - 1] = 0;
ans[n - 1] = n - 1;
// Make each word first
// word of line by iterating
// over each index in arr.
for (i = n - 2; i >= 0; i--)
{
currlen = -1;
dp[i] = Integer.MAX_VALUE;
// Keep on adding words in
// current line by iterating
3012
Chapter 421. Word Wrap problem ( Space optimized solution )
3013
Chapter 421. Word Wrap problem ( Space optimized solution )
Output:
1 1 2 3 4 4
Source
https://www.geeksforgeeks.org/word-wrap-problem-space-optimized-solution/
3014
Chapter 422
Input : n = 6
Output : 5
Input : n = 10
Output : 13
We first store 0, 1, 2, 3, 4, 5 in an array. We can see that next numbers will be 10, 11,
12„13, 14, 15 and after that numbers will be 20, 21, 23, 24, 25 and so on. We can see
the pattern that is repeating again and again. We save the calculated result and use it for
further calculations.
next 6 numbers are-
1*10+0 = 10
1*10+1 = 11
1*10+2 = 12
1*10+3 = 13
1*10+4 = 14
1*10+5 = 15
and after that next 6 numbers will be-
2*10+0 = 20
2*10+1 = 21
2*10+2 = 22
3015
Chapter 422. n-th number with digits in {0, 1, 2, 3, 4, 5}
2*10+3 = 23
2*10+4 = 24
2*10+5 = 25
We use this pattern to find the n-th number. Below is complete algorithm.
3) print ans[n-1]
3016
Chapter 422. n-th number with digits in {0, 1, 2, 3, 4, 5}
Efficient Method :
Algorithm :
1. First convert number n to base 6.
2. Store the converted value simultaneously in an array.
3. Print that array in reverse order.
Below is the implementation of above algorithm :
C++
3017
Chapter 422. n-th number with digits in {0, 1, 2, 3, 4, 5}
Java
3018
Chapter 422. n-th number with digits in {0, 1, 2, 3, 4, 5}
{
// initialize an array to 0
int arr[] = new int[max];
int n = 10;
// function calling to convert
// number n to base 6
int size = baseconversion(arr, n - 1, 6);
// if size is zero then return zero
if (size == 0)
System.out.print(size);
for (int i = size - 1; i >= 0; i--) {
System.out.print(arr[i]);
}
}
}
// This code is contributed by Anant Agarwal.
C#
3019
Chapter 422. n-th number with digits in {0, 1, 2, 3, 4, 5}
}
return i;
}
// Driver code
public static void Main ()
{
// initialize an array to 0
int []arr = new int[max];
int n = 10;
// function calling to convert
// number n to base 6
int size = baseconversion(arr, n - 1, 6);
// if size is zero then return zero
if (size == 0)
Console.Write(size);
for (int i = size - 1; i >= 0; i--) {
Console.Write(arr[i]);
}
}
}
// This code is contributed by nitin mittal
Output:
13
Source
https://www.geeksforgeeks.org/n-th-number-with-digits-in-0-1-2-3-4-5/
3020