Dynamic Programming-1
Dynamic Programming-1
Given an integer array of coins[ ] of size N representing different types of currency and an
integer sum, The task is to find the number of ways to make sum by using different
combinations from coins[].
Note: Assume that you have an infinite supply of each type of coin.
Solution:
Input : 3
Output : 4
Explanation:
1 step + 2 step
2 step + 1 step
3 step
Solution:
// Base Case
if (n == 0)
return 1;
else if (n < 0)
return 0;
Space Complexity: O(n). To store the values in a DP, n extra space is needed. Also, stack space for
recursion is needed which is again O(n)
3. Given an array arr[] of size N, the task is to find the length of the Longest Increasing
Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the
subsequence are sorted in increasing order.
Input: arr[] = {3, 10, 2, 1, 20}
Output: 3
Explanation: The longest increasing subsequence is 3, 10, 20
Solution:
int[][] dp)
{
if (idx == n) {
return 0;
}
if (dp[idx][prev_idx + 1] != -1) {
return dp[idx][prev_idx + 1];
}
return dp[idx][prev_idx + 1]
= Math.max(take, notTake);
}
// The wrapper function for _lis()
static int lis(int arr[], int n)
{
// The function _lis() stores its result in max
int dp[][] = new int[n + 1][n + 1];
for (int row[] : dp)
Arrays.fill(row, -1);
4. Given a set of non-negative integers, and a value sum, determine if there is a subset of the
given set with sum equal to given sum.
Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
Output: True
There is a subset (4, 5) with sum 9.
Solution:
if (n <= 0)
return 0;
TC: O(n*sum)
SC: O(n*sum)
5. Given a n*n matrix where all numbers are distinct, find the maximum length path (starting
from any cell) such that all cells along the path are in increasing order with a difference of 1.
We can move in 4 directions from a given cell (i, j), i.e., we can move to (i+1, j) or (i, j+1) or (i-
1, j) or (i, j-1) with the condition that the adjacent cells have a difference of 1.
Example:
Solution:
private static int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // Possible directions: right, down, left,
up
int maxLength = 0;
int n = matrix.length;
// Create a memoization map to store the already computed maximum lengths for each cell
// Iterate through each cell and find the maximum length starting from that cell
return maxLength;
private static int dfs(int[][] matrix, int i, int j, Map<String, Integer> memo) {
int n = matrix.length;
// If the maximum length starting from this cell is already computed, return it from memoization
if (memo.containsKey(key))
return memo.get(key);
int maxLength = 1;
// Check if the new cell is within bounds and has a difference of 1 with the current cell
if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < n &&
matrix[newRow][newCol] - matrix[i][j] == 1) {
memo.put(key, maxLength);
return maxLength;