Skip to content

Commit a76750c

Browse files
[CPP] 121. Best Time to Buy and Sell Stock
1 parent dac1764 commit a76750c

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public:
3+
int maxProfit(vector<int>& prices) {
4+
int n = prices.size();
5+
// Preprocessing
6+
// Polulate a smallest from beginning array
7+
// Polulate a largest from the end array
8+
vector<int> smallest(n, -1), largest(n, -1);
9+
10+
smallest[0] = prices[0];
11+
largest[n-1] = prices[n-1];
12+
13+
for (int i = 1; i < n; i++) {
14+
smallest[i] = min(smallest[i-1], prices[i]);
15+
}
16+
17+
for (int i = n-2; i>=0; i--) {
18+
largest[i] = max(largest[i+1], prices[i]);
19+
}
20+
21+
// Logic
22+
// Max difference b/w the smallest and largest element
23+
int res = 0;
24+
for(int i=0; i<n; i++) res = max(res, largest[i]-smallest[i]);
25+
26+
return res;
27+
28+
}
29+
};

0 commit comments

Comments
 (0)