Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Code for Best Time To Buy and Sell Stocks and Added Different Error Page Templates #211

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#include "bits/stdc++.h"
using namespace std;

int solve(vector<int> &prices, int k)
{
int n = prices.size();
if (k >= n / 2)
{
int profit = 0;
for (int i = 1; i < n; i++)
if (prices[i] > prices[i - 1])
profit += prices[i] - prices[i - 1];
return profit;
}

vector<int> buy(k + 1, INT_MIN);
vector<int> sell(k + 1, 0);

int ans = 0;
for (int i = 0; i < n; i++)
{
for (int j = 1; j <= k; j++)
{
buy[j] = max(buy[j], sell[j - 1] - prices[i]);
sell[j] = max(sell[j], buy[j] + prices[i]);
}
}

return sell[k];
}
19 changes: 19 additions & 0 deletions DSA/Cpp/Dynamic_Programming/Best Time to Buy and Sell Stocks I.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#include <bits/stdc++.h>
using namespace std;

int maxProfit(const vector<int> &A)
{
int minVal = INT_MAX;
int maxProfit = 0;

for (int i = 0; i < A.size(); i++)
{
if (A[i] < minVal)
minVal = A[i];
else
{
maxProfit = max(maxProfit, A[i] - minVal);
}
}
return maxProfit;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#include "bits/stdc++.h"
using namespace std;

int Solution::maxProfit(const vector<int> &A)
{
if (A.size() == 0)
return 0;
int min = A[0];
int sum = 0;
for (int i = 1; i < A.size(); i++)
{
if (A[i] < min)
{
min = A[i];
}
if (A[i] > min)
{
sum = sum + A[i] - min;
min = A[i];
}
}
return sum;
}