From 51252f28fc2fc20de96a8785d19b56dd4509435f Mon Sep 17 00:00:00 2001 From: rishigoswamy Date: Thu, 12 Feb 2026 15:34:51 -0800 Subject: [PATCH] Add implementation for leetcode problems 198, 322 --- leetcode198.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ leetcode322.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 leetcode198.py create mode 100644 leetcode322.py diff --git a/leetcode198.py b/leetcode198.py new file mode 100644 index 00000000..8eab499e --- /dev/null +++ b/leetcode198.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Thu Feb 12 15:33:04 2026 + +@author: rishigoswamy + + Problem: House Robber + Link: https://leetcode.com/problems/house-robber/ + + Description: + You are given an integer array nums representing the amount of money + at each house. Adjacent houses cannot be robbed. + Return the maximum amount of money you can rob. + + Approach: + Optimized Dynamic Programming (Space Optimized). + + Let: + r1 = max money till house i-2 + r2 = max money till house i-1 + + For each house: + current = max(r1 + num, r2) + + Shift: + r1 = r2 + r2 = current + + Time Complexity: O(n) + Space Complexity: O(1) + +""" + +class Solution: + def rob(self, nums: List[int]) -> int: + r1, r2 = 0, 0 + for num in nums: + temp = max(r1 + num, r2) + r1 = r2 + r2 = temp + return r2 + + diff --git a/leetcode322.py b/leetcode322.py new file mode 100644 index 00000000..79c50a51 --- /dev/null +++ b/leetcode322.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Thu Feb 12 15:30:44 2026 + +@author: rishigoswamy + + Problem: Coin Change + Link: https://leetcode.com/problems/coin-change/ + + Description: + Given an integer array coins representing coin denominations + and an integer amount representing a total amount of money, + return the fewest number of coins needed to make up that amount. + If that amount cannot be made up, return -1. + + Approach: + Bottom-Up Dynamic Programming. + + - dp[i] represents the minimum coins needed to make amount i. + - Initialize dp with a large value (amount + 1). + - Base case: dp[0] = 0. + - For each amount, try every coin and update dp. + + Time Complexity: O(amount * number_of_coins) + Space Complexity: O(amount) + +""" + +class Solution: + def coinChange(self, coins, amounts: int) -> int: + dp = [amounts + 1] * (amounts + 1) + dp[0] = 0 + for amount in range(1, amounts + 1): + for coin in coins: + if amount - coin >= 0: + dp[amount] = min(dp[amount], 1 + dp[amount - coin]) + return dp[-1] if dp[-1] != amounts+1 else -1 + \ No newline at end of file