Skip to content

Commit 6bceb9c

Browse files
find3rskeepertstreamDOTh
authored andcommitted
added code for best time to buy sell stock (#136)
1 parent 761dc79 commit 6bceb9c

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*@author Navneet Jain
2+
* Say you have an array for which the ith element is the price of a given stock on day i.
3+
* 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.
4+
5+
*/
6+
#include<iostream>
7+
#include<vector>
8+
#include<climits>
9+
using namespace std;
10+
11+
int maxProfit(const vector<int> &A) {
12+
int buy = A[0], flag = 0, i = 1, max_sell = INT_MIN;
13+
int sol = 0;
14+
while(i < A.size()){
15+
int diff = A[i] - A[i-1];
16+
//It's a greedy appoach. If current diff is greater than 0, then add that to the solution.
17+
if(diff > 0){
18+
sol = sol + diff;
19+
}
20+
i++;
21+
}
22+
23+
return sol;
24+
}
25+
26+
int main(){
27+
vector<int> A = {1,2};
28+
cout << maxProfit(A);
29+
}

Diff for: Dynamic Programming/buy_sell_stocks/README.md

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
Problem Statement:
2+
Say you have an array for which the ith element is the price of a given stock on day i.
3+
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.
4+
5+
Solution Approach:
6+
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.
7+
So essentially at every index i, you need to find the maximum in the array in the suffix.
8+
Now this part can be done in 2 ways :
9+
1) Have another array which stores that information.
10+
max[i] = max(max[i+1], A[i])
11+
12+
2) Start processing entries from the end maintaining a maximum till now. Constant additional space requirement.
13+
14+

0 commit comments

Comments
 (0)