Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Cpp/Dynamic Programming/ClimbingStairs.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include<iostream>

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/

*/
50 changes: 50 additions & 0 deletions Cpp/Dynamic Programming/max_stock_profit.cpp
Original file line number Diff line number Diff line change
@@ -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<iostream>
#include<vector>

using namespace std;

int maxProfit(vector<int>&prices);

// Driver Code

int main()
{
int n;
cin >> n;
vector<int> prices(n);
for(int i=0;i<n;i++)
{
cin >> prices[i];
}

cout << maxProfit(prices) << endl;;
}

// Implemented function for the solution.

int maxProfit(vector<int> &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<n;i++)
{
minPriceSoFar = min(minPriceSoFar,prices[i]);
int profit = prices[i] - minPriceSoFar; // Stores the profit for each day after selling.
maxProfit = max(maxProfit,profit);
}
return maxProfit;
}