DP #26. Buy Sell Stock I - mbhushan/dynpro GitHub Wiki
(26). Buy Sell Stock - I
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.
index |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
prices |
2 |
5 |
7 |
1 |
4 |
3 |
1 |
3 |
|
|
|
|
|
|
|
|
|
Max profit |
null |
3 |
5 |
5 |
5 |
5 |
5 |
5 |
min so far |
|
2 |
2 |
1 |
1 |
1 |
1 |
1 |
min = prices[0];
profit = Integer.MIN_VALUE;
for (int i=1; i<prices.length; i++) {
profit = Max(profit, prices[i] - min);
min = Min(min, prices[i]);
}
Buy Sell - 1 Transaction
- Time Complexity: O(n)
- Space Complexity: O(1)