Dynamic Programming

Dynamic Programming

180 questions spanning the full range of dynamic programming — 1D and 2D DP, interval DP, tree DP, digit DP, and bitmask DP.

Best Time to Buy and Sell Stock

easy
You are given an array prices where prices[i] is the price of a given stock on the ith day.

Climbing Stairs

easy
You are climbing a staircase.

Counting Bits

easy
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.

Divisor Game

easy
Alice and Bob take turns playing a game, with Alice starting first.

Fibonacci Number

easy
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.

Is Subsequence

easy
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

Longest Unequal Adjacent Groups Subsequence I

easy
You are given a string array words and a binary array groups both of length n.

Maximum Repeating Substring

easy
For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence.

Min Cost Climbing Stairs

easy
You are given an integer array cost where cost[i] is the cost of ith step on a staircase.

N-th Tribonacci Number

easy
The Tribonacci sequence Tn is defined as follows: T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.

Pascal's Triangle

easy
Given an integer numRows, return the first numRows of Pascal's triangle.

Pascal's Triangle II

easy
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.

01 Matrix

medium
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

2 Keys Keyboard

medium
There is only one character 'A' on the screen of a notepad.

Airplane Seat Assignment Probability

medium
n passengers board an airplane with exactly n seats.

Apply Operations to Make Two Strings Equal

medium
You are given two 0-indexed binary strings s1 and s2, both of length n, and a positive integer x.

Arithmetic Slices

medium
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

As Far from Land as Possible

medium
Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized,...

Beautiful Arrangement

medium
Suppose you have n integers labeled 1 through n.

Best Sightseeing Pair

medium
You are given an integer array values where values[i] represents the value of the ith sightseeing spot.

Best Team With No Conflicts

medium
You are the manager of a basketball team.

Best Time to Buy and Sell Stock II

medium
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

Best Time to Buy and Sell Stock V

medium
You are given an integer array prices where prices[i] is the price of a stock in dollars on the ith day, and an integer k.

Best Time to Buy and Sell Stock with Cooldown

medium
You are given an array prices where prices[i] is the price of a given stock on the ith day.

Best Time to Buy and Sell Stock with Transaction Fee

medium
You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.

Binary Trees With Factors

medium
Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.

Bitwise ORs of Subarrays

medium
Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr.

Can I Win

medium
In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10.

Champagne Tower

medium
We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.

Cheapest Flights Within K Stops

medium
There are n cities connected by some number of flights.

Check if it is Possible to Split Array

medium
You are given an array nums of length n and an integer m.

Check if There is a Valid Partition For The Array

medium
You are given a 0-indexed integer array nums.

Closest Dessert Cost

medium
You would like to make dessert and are preparing to buy the ingredients.

Coin Change

medium
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Coin Change II

medium
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Combination Sum IV

medium
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.

Construct the Longest New String

medium
You are given three integers x, y, and z.

Count Beautiful Splits in an Array

medium
You are given an array nums.

Count Number of Teams

medium
There are n soldiers standing in a line.

Count Number of Texts

medium
Alice is texting Bob using her phone.

Count Number of Ways to Place Houses

medium
There is a street with n * 2 plots, where there are n plots on each side of the street.

Count Numbers with Unique Digits

medium
Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.

Count Partitions With Max-Min Difference at Most K

medium
You are given an integer array nums and an integer k.

Count Paths With the Given XOR Value

medium
You are given a 2D integer array grid with size m x n.

Count Sorted Vowel Strings

medium
Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.

Count Submatrices With All Ones

medium
Given an m x n binary matrix mat, return the number of submatrices that have all ones.

Count Substrings That Differ by One Character

medium
Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting...

Count the Number of Square-Free Subsets

medium
You are given a positive integer 0-indexed array nums.

Count Ways To Build Good Strings

medium
Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following: This can be...

Decode Ways

medium
You have intercepted a secret message encoded as a string of numbers.

Decremental String Concatenation

medium
You are given a 0-indexed array words containing n strings.

Delete and Earn

medium
You are given an integer array nums.

Delete Operation for Two Strings

medium
Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.

Different Ways to Add Parentheses

medium
Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators.

Disconnect Path in a Binary Matrix by at Most One Flip

medium
You are given a 0-indexed m x n binary matrix grid.

Domino and Tromino Tiling

medium
You have two types of tiles: a 2 x 1 domino shape and a tromino shape.

Edit Distance

medium
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

Egg Drop With 2 Eggs and N Floors

medium
You are given two identical eggs and you have access to a building with n floors labeled from 1 to n.

Extra Characters in a String

medium
You are given a 0-indexed string s and a dictionary of words dictionary.

Fair Distribution of Cookies

medium
You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag.

Filling Bookcase Shelves

medium
You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book.

Find All Good Indices

medium
You are given a 0-indexed integer array nums of size n and a positive integer k.

Find All Possible Stable Binary Arrays I

medium
You are given 3 positive integers zero, one, and limit.

Find Good Days to Rob the Bank

medium
You and a gang of thieves are planning on robbing a bank.

Find Maximum Number of Non Intersecting Substrings

medium
You are given a string word.

Find Maximum Removals From Source String

medium
You are given a string source of size n, a string pattern that is a subsequence of source, and a sorted integer array targetIndices that contains distinct numbers in the range [0,...

Find Minimum Cost to Remove Array Elements

medium
You are given an integer array nums.

Find the City With the Smallest Number of Neighbors at a Threshold Distance

medium
There are n cities numbered from 0 to n-1.

Find the Lexicographically Smallest Valid Sequence

medium
You are given two strings word1 and word2.

Find the Maximum Length of a Good Subsequence I

medium
You are given an integer array nums and a non-negative integer k.

Find the Maximum Length of Valid Subsequence I

medium
A subsequence sub of nums with length x is called valid if it satisfies: Return the length of the longest valid subsequence of nums.

Find the Maximum Length of Valid Subsequence II

medium
A subsequence sub of nums with length x is called valid if it satisfies:

Find the Substring With Maximum Cost

medium
You are given a string s, a string chars of distinct characters and an integer array vals of the same length as chars.

Find Two Non-overlapping Sub-arrays Each With Target Sum

medium
You are given an array of integers arr and an integer target.

Find X Value of Array I

medium
You are given an array of positive integers nums, and a positive integer k.

First Day Where You Have Been in All the Rooms

medium
There are n rooms you need to visit, labeled from 0 to n - 1.

Flip String to Monotone Increasing

medium
A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none).

Generate Parentheses

medium
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Greatest Sum Divisible by Three

medium
Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.

Guess Number Higher or Lower II

medium
We are playing the Guessing Game.

House Robber

medium
You are a professional robber planning to rob houses along a street.

House Robber II

medium
You are a professional robber planning to rob houses along a street.

House Robber IV

medium
There are several consecutive houses along a street, each of which has some money inside.

Integer Break

medium
Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.

Integer Replacement

medium
Given a positive integer n, you can apply one of the following operations: Return the minimum number of operations needed for n to become 1.

Interleaving String

medium
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.

Inverse Coin Change

medium
You are given a 1-indexed integer array numWays, where numWays[i] represents the number of ways to select a total amount i using an infinite supply of some fixed coin denominations.

Jump Game

medium
You are given an integer array nums.

Jump Game II

medium
You are given a 0-indexed array of integers nums of length n.

Jump Game VI

medium
You are given a 0-indexed integer array nums and an integer k.

Jump Game VII

medium
You are given a 0-indexed binary string s and two integers minJump and maxJump.

K-Concatenation Maximum Sum

medium
Given an integer array arr and an integer k, modify the array by repeating it k times.

Knight Dialer

medium
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming...

Knight Probability in Chessboard

medium
On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves.

Largest 1-Bordered Square

medium
Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.

Largest Divisible Subset

medium
Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies: If there are...

Largest Plus Sign

medium
You are given an integer n.

Largest Sum of Averages

medium
You are given an integer array nums and an integer k.

Last Stone Weight II

medium
You are given an array of integers stones where stones[i] is the weight of the ith stone.

Length of Longest Fibonacci Subsequence

medium
A sequence x1, x2, ..., xn is Fibonacci-like if: Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like...

Length of the Longest Subsequence That Sums to Target

medium
You are given a 0-indexed array of integers nums, and an integer target.

Longest Arithmetic Subsequence

medium
Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.

Longest Arithmetic Subsequence of Given Difference

medium
Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent...

Longest Binary Subsequence Less Than or Equal to K

medium
You are given a binary string s and a positive integer k.

Longest Common Subsequence

medium
Given two strings text1 and text2, return the length of their longest common subsequence.

Longest Ideal Subsequence

medium
You are given a string s consisting of lowercase letters and an integer k.

Longest Increasing Subsequence

medium
Given an integer array nums, return the length of the longest strictly increasing subsequence.

Longest Mountain in Array

medium
You may recall that an array arr is a mountain array if and only if: Given an integer array arr, return the length of the longest subarray, which is a mountain.

Longest Non-decreasing Subarray From Two Arrays

medium
You are given two 0-indexed integer arrays nums1 and nums2 of length n.

Longest Palindrome After Substring Concatenation I

medium
You are given two strings, s and t.

Longest Palindromic Subsequence

medium
Given a string s, find the longest palindromic subsequence's length in s.

Longest Palindromic Subsequence After at Most K Operations

medium
You are given a string s and an integer k.

Longest Palindromic Substring

medium
Given a string s, return the longest palindromic substring in s.

Longest Square Streak in an Array

medium
You are given an integer array nums.

Longest String Chain

medium
You are given an array of words where each word consists of lowercase English letters.

Longest Subarray of 1's After Deleting One Element

medium
Given a binary array nums, you should delete one element from it.

Longest Subsequence With Decreasing Adjacent Difference

medium
You are given an array of integers nums.

Longest Turbulent Subarray

medium
Given an integer array arr, return the length of a maximum size turbulent subarray of arr.

Longest Unequal Adjacent Groups Subsequence II

medium
You are given a string array words, and an array groups, both arrays having length n.

Make Costs of Paths Equal in a Binary Tree

medium
You are given an integer n representing the number of nodes in a perfect binary tree consisting of nodes numbered from 1 to n.

Matchsticks to Square

medium
You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick.

Maximal Square

medium
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

Maximize the Profit as the Salesman

medium
You are given an integer n representing the number of houses on a number line, numbered from 0 to n - 1.

Maximize Total Cost of Alternating Subarrays

medium
You are given an integer array nums with length n.

Maximum Absolute Sum of Any Subarray

medium
You are given an integer array nums.

Maximum Alternating Subsequence Sum

medium
The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.

Maximum Amount of Money Robot Can Earn

medium
You are given an m x n grid.

Maximum and Minimum Sums of at Most Size K Subsequences

medium
You are given an integer array nums and a positive integer k.

Maximum Compatibility Score Sum

medium
There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes).

Maximum Difference Score in a Grid

medium
You are given an m x n matrix grid consisting of positive integers.

Maximum Earnings From Taxi

medium
There are n points on a road you are driving your taxi on.

Maximum Energy Boost From Two Drinks

medium
You are given two integer arrays energyDrinkA and energyDrinkB of the same length n by a futuristic sports scientist.

Maximum Frequency After Subarray Operation

medium
You are given an array nums of length n.

Maximum Length of Pair Chain

medium
You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.

Maximum Length of Repeated Subarray

medium
Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.

Maximum Length of Subarray With Positive Product

medium
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.

Maximum Multiplication Score

medium
You are given an integer array a of size 4 and another integer array b of size at least 4.

Maximum Non Negative Product in a Matrix

medium
You are given a m x n matrix grid.

Maximum Number of Jumps to Reach the Last Index

medium
You are given a 0-indexed array nums of n integers and an integer target.

Maximum Number of Moves in a Grid

medium
You are given a 0-indexed m x n matrix grid consisting of positive integers.

Maximum Number of Operations With the Same Score II

medium
Given an array of integers called nums, you can perform any of the following operation while nums contains at least 2 elements: The score of the operation is the sum of the...

Maximum Number of Points with Cost

medium
You are given an m x n integer matrix points (0-indexed).

Maximum Number That Sum of the Prices Is Less Than or Equal to K

medium
You are given an integer k and an integer x.

Maximum Points Tourist Can Earn

medium
You are given two integers, n and k, along with two 2D integer arrays, stayScore and travelScore.

Maximum Product of the Length of Two Palindromic Subsequences

medium
Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized.

Maximum Product Subarray

medium
Given an integer array nums, find a subarray that has the largest product, and return the product.

Maximum Score After Applying Operations on a Tree

medium
There is an undirected tree with n nodes labeled from 0 to n - 1, and rooted at node 0.

Maximum Strength of a Group

medium
You are given a 0-indexed integer array nums representing the score of students in an exam.

Maximum Subarray

medium
Find the contiguous subarray with the largest sum.

Maximum Subarray Sum with One Deletion

medium
Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion.

Maximum Sum Circular Subarray

medium
Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.

Maximum Sum of Two Non-Overlapping Subarrays

medium
Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen.

Maximum Total Damage With Spell Casting

medium
A magician has various spells.

Maximum Total Reward Using Operations I

medium
You are given an integer array rewardValues of length n, representing the values of rewards.

Maximum Weighted K-Edge Path

medium
You are given an integer n and a Directed Acyclic Graph (DAG) with n nodes labeled from 0 to n - 1.

Minimize Maximum of Array

medium
You are given a 0-indexed array nums comprising of n non-negative integers.

Minimize the Difference Between Target and Chosen Elements

medium
You are given an m x n integer matrix mat and an integer target.

Minimize the Maximum Difference of Pairs

medium
You are given a 0-indexed integer array nums and an integer p.

Minimum Additions to Make Valid String

medium
Given a string word to which you can insert letters "a", "b" or "c" anywhere and any number of times, return the minimum number of letters that must be inserted so that word...

Minimum Array Sum

medium
You are given an integer array nums and three integers k, op1, and op2.

Minimum ASCII Delete Sum for Two Strings

medium
Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.

Minimum Cost for Cutting Cake I

medium
There is an m x n cake that needs to be cut into 1 x 1 pieces.

Minimum Cost For Tickets

medium
You have planned some train traveling one year in advance.

Minimum Cost Path with Alternating Directions II

medium
You are given two integers m and n representing the number of rows and columns of a grid, respectively.

Minimum Cost to Make All Characters Equal

medium
You are given a 0-indexed binary string s of length n on which you can apply two types of operations: Return the minimum cost to make all characters of the string equal.

Minimum Cost Tree From Leaf Values

medium
Given an array arr of positive integers, consider all binary trees such that: Among all possible binary trees considered, return the smallest possible sum of the values of each...

Minimum Deletions to Make String Balanced

medium
You are given a string s consisting only of characters 'a' and 'b'​​​​.

Minimum Falling Path Sum

medium
Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.

Minimum Increment Operations to Make Array Beautiful

medium
You are given a 0-indexed integer array nums having length n, and an integer k.

Minimum Increments to Equalize Leaf Paths

medium
You are given an integer n and an undirected tree rooted at node 0 with n nodes numbered from 0 to n - 1.

Minimum Jumps to Reach Home

medium
A certain bug's home is on the x-axis at position x.

Minimum Moves to Spread Stones Over Grid

medium
You are given a 0-indexed 2D integer matrix grid of size 3 * 3, representing the number of stones in each cell.

Minimum Number of Coins for Fruits

medium
You are given an 0-indexed integer array prices where prices[i] denotes the number of coins needed to purchase the (i + 1)th fruit.

Minimum Number of Flips to Make the Binary String Alternating

medium
You are given a binary string s.

Minimum Number of Food Buckets to Feed the Hamsters

medium
You are given a 0-indexed string hamsters where hamsters[i] is either: You will add some number of food buckets at the empty indices in order to feed the hamsters.

Minimum Number of Operations to Make X and Y Equal

medium
You are given two positive integers x and y.

Minimum Number of Operations to Satisfy Conditions

medium
You are given a 2D matrix grid of size m x n.

Minimum Number of Valid Strings to Form Target I

medium
You are given an array of strings words and a string target.

Minimum Number of Work Sessions to Finish the Tasks

medium
There are n tasks assigned to you.

Minimum Operations to Make Binary Array Elements Equal to One II

medium
You are given a binary array nums.