forked from Asiatik/codezilla
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added code for best time to buy sell stock (Asiatik#136)
- Loading branch information
1 parent
761dc79
commit 6bceb9c
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
29 changes: 29 additions & 0 deletions
29
Dynamic Programming/buy_sell_stocks/C++/buy_sell_stock_dp.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/*@author Navneet Jain | ||
* Say you have an array for which the ith element is the price of a given stock on day i. | ||
* If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. | ||
*/ | ||
#include<iostream> | ||
#include<vector> | ||
#include<climits> | ||
using namespace std; | ||
|
||
int maxProfit(const vector<int> &A) { | ||
int buy = A[0], flag = 0, i = 1, max_sell = INT_MIN; | ||
int sol = 0; | ||
while(i < A.size()){ | ||
int diff = A[i] - A[i-1]; | ||
//It's a greedy appoach. If current diff is greater than 0, then add that to the solution. | ||
if(diff > 0){ | ||
sol = sol + diff; | ||
} | ||
i++; | ||
} | ||
|
||
return sol; | ||
} | ||
|
||
int main(){ | ||
vector<int> A = {1,2}; | ||
cout << maxProfit(A); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
Problem Statement: | ||
Say you have an array for which the ith element is the price of a given stock on day i. | ||
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. | ||
|
||
Solution Approach: | ||
If you buy your stock on day i, you’d obviously want to sell it on the day its price is maximum after that day. | ||
So essentially at every index i, you need to find the maximum in the array in the suffix. | ||
Now this part can be done in 2 ways : | ||
1) Have another array which stores that information. | ||
max[i] = max(max[i+1], A[i]) | ||
|
||
2) Start processing entries from the end maintaining a maximum till now. Constant additional space requirement. | ||
|
||
|