-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL121.java
More file actions
22 lines (22 loc) · 823 Bytes
/
L121.java
File metadata and controls
22 lines (22 loc) · 823 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution121 {
class Solution {
/**
* 121. Best Time to Buy and Sell Stock https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
*
* @param prices
* @return Maximum profit that can be made
* @timeComplexity O(n)
* @spaceComplexity O(1)
*/
public int maxProfit(int[] prices) {
// At every point in the array, we maintain two values - maxProfit so far, and minimum price seen so far
int maxProfit = 0;
int minValue = Integer.MAX_VALUE;
for (int i = 0; i < prices.length; i++) {
maxProfit = Math.max(maxProfit, prices[i] - minValue);
minValue = Math.min(prices[i], minValue);
}
return maxProfit;
}
}
}