Skip to content

Commit

Permalink
added code for best time to buy sell stock (Asiatik#136)
Browse files Browse the repository at this point in the history
  • Loading branch information
find3rskeeper authored and tstreamDOTh committed Oct 31, 2018
1 parent 761dc79 commit 6bceb9c
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Dynamic Programming/buy_sell_stocks/C++/buy_sell_stock_dp.cpp
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);
}
14 changes: 14 additions & 0 deletions Dynamic Programming/buy_sell_stocks/README.md
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.


0 comments on commit 6bceb9c

Please sign in to comment.