Skip to content

Commit 5afef48

Browse files
authored
Create Q-01: Best Time to Buy and Sell Stock I.java
1 parent 7a26952 commit 5afef48

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
121. Best Time to Buy and Sell Stock
3+
4+
You are given an array prices where prices[i] is the price of a given stock on the ith day.
5+
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
6+
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
7+
8+
Example 1:
9+
Input: prices = [7,1,5,3,6,4]
10+
Output: 5
11+
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
12+
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
13+
14+
Example 2:
15+
Input: prices = [7,6,4,3,1]
16+
Output: 0
17+
Explanation: In this case, no transactions are done and the max profit = 0.
18+
19+
Constraints:
20+
1 <= prices.length <= 105
21+
0 <= prices[i] <= 104
22+
*/
23+
// TC : O(n) SC: O(1)
24+
25+
import java.util.* ;
26+
27+
public class Solution{
28+
public static int maximumProfit(ArrayList<Integer> prices){
29+
// Write your code here.
30+
int mini=prices.get(0);
31+
int profit=0;
32+
for(int i=0;i<prices.size();i++){
33+
int maxi = prices.get(i)-mini;
34+
profit =Math.max(maxi,profit);
35+
mini =Math.min(prices.get(i),mini);
36+
}
37+
return profit;
38+
}
39+
}

0 commit comments

Comments
 (0)