198. House Robber - LeetCode Approach: Consider two states—robbing or skipping the current house—and choose the one yielding the maximum value. Use dynamic programming with the recurrence: dp[i] = max(dp[i-1], dp[i-2] + nums[i]). class Solution { public: int rob(vector<int>& nums) { int n...
0-1 Knapsack Problem with Rolling Array Optimization Understanding the Problem The 0-1 knapsack problem is a classic optimization challenge where we aim to maximize the value of items placed in a knapsack with a fixed capacity. Each item can either be included (1) or not included (0), hence the name...
LeetCode 300: Longest Increasing Subsequence Given an integer array nums, find the length of the longest strictly increasing subsequence. A subsequence is a sequence derived from an array by deleting some or no elements without changing the order of remaining elements. Dynamic Programming Approach D...
Given a binary string composed of '0', '1', and '?' characters, and a lookup table f that maps each 3-bit binary number (from 0 to 7) too either 0 or 1, determine the number of ways to replace all '?' characters with '0' or '1' such that the resulting string can be reduced to "1" using the...
Algorithm ApproachLet dp[m][n] denote the length of the longest common subsequence between the first m characters of string str_a and the first n characters of string str_b. By utilizing an extra row and column for empty prefixes, the base cases naturally become dp[0][n] = 0 and dp[m][0] = 0.The sta...
Introduction Dynamic programming problems that rely on transitions between adjacant elements often cannot be solved using standard DP approaches. In such cases, linear segment DP proves useful. Also known as continuous segment DP, this technique focuses on maintaining the total contribution of vario...
Palindromic Substrings Problem Statement Given a string, count how many palindromic substrings it contains. Substrings that start or end at different positions are considered distinct even if they consist of the same characters. Solution using Dynamic Programming We define a two‑dimensional Boolean...
Fibonacci Number (LeetCode 509) The Fibonacci seqeunce is defined as: F(0) = 0 F(1) = 1 F(n) = F(n - 1) + F(n - 2) for n > 1 Example: Input: n = 4 Output: 3 (Sequence: 0, 1, 1, 2, 3) Solution using constant space: class Solution: def fib(self, n: int) -> int: if n < 2: return n # Initialize...
Greeting Code #include <iostream> int main() { std::cout << "Competition Day!" << '\n'; return 0; } Neighbor Sum Array #include <iostream> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int len; cin >>...
A knapsack problem involves selecting items with given weights and values to maximize total value without exceeding a capacity limit. It appears in resource allocation, scheduling, logistics, and investment scenarios. Problem Categories Binary Knapsack — Each item can be taken at most once. Given n...