diff --git a/Cpp/Dynamic Programming/ClimbingStairs.cpp b/Cpp/Dynamic Programming/ClimbingStairs.cpp new file mode 100644 index 0000000..3573487 --- /dev/null +++ b/Cpp/Dynamic Programming/ClimbingStairs.cpp @@ -0,0 +1,43 @@ +#include + +using namespace std; + +int ClimbStairs(int n); + +int main() +{ + cout << "Enter the number of stairs: "; + int n; + cin >> n; + cout << ClimbStairs(n) << endl; +} + +int ClimbStairs(int n) +{ + int dp[n+1]; + dp[0] = 1; // If there the stairs are 0 and 1 in number, then the possible ways to climb are 1 and 1 respectively. + dp[1] = 1; + for(int i=2;i<=n;i++) + { + dp[i] = dp[i-1] + dp[i-2]; // To climb to nth stairs, the number of ways depends on the number of ways to climb (n-1)th and (n-2)th stairs + } + return dp[n]; +} + + /* + + *** Test Case 1 *** + + Enter the number of stairs: 6 + + 13 + + *** Test Case 2 *** + + Enter the number of stairs: 56 + + 363076002 + + Link to the problem: https://leetcode.com/problems/climbing-stairs/ + + */ \ No newline at end of file diff --git a/Cpp/Dynamic Programming/max_stock_profit.cpp b/Cpp/Dynamic Programming/max_stock_profit.cpp new file mode 100644 index 0000000..79aa3f3 --- /dev/null +++ b/Cpp/Dynamic Programming/max_stock_profit.cpp @@ -0,0 +1,50 @@ +// Program to find the maximum profit when tradiing in a stock + +// PROBLEM STATEMENT + +/* + You are given an array prices where prices[i] is the price of a given stock on the ith day. + + You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. + + Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. +*/ + +#include +#include + +using namespace std; + +int maxProfit(vector&prices); + +// Driver Code + +int main() +{ + int n; + cin >> n; + vector prices(n); + for(int i=0;i> prices[i]; + } + + cout << maxProfit(prices) << endl;; +} + +// Implemented function for the solution. + +int maxProfit(vector &prices) +{ + int n = prices.size(); + int minPriceSoFar = INT32_MAX; // Stores the minimum price of a stock till the selling day + int maxProfit = INT32_MIN; // Stores the final answer of maximum profit. + + for(int i=0;i