Skip to content

Commit fa78dbd

Browse files
authored
Merge pull request #139 from jayalloyd/feature/java-stock-profit
feat(java): Add O(n) solution for Buy and Sell Stock problem to Arrays
2 parents 70fa619 + 6dfcc7b commit fa78dbd

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
public class BuyAndSellStockCode {
2+
public static int buyAndSellStock(int []prices){
3+
4+
int buyPrice=Integer.MAX_VALUE;
5+
6+
int maxProfit=0;
7+
//track lowest buying price
8+
for(int i=0;i<prices.length;i++){
9+
if(buyPrice<prices[i]){//profit
10+
int profit=prices[i]-buyPrice;
11+
maxProfit=Math.max(maxProfit, profit);//todays profit
12+
13+
14+
}else {
15+
16+
buyPrice=prices[i];
17+
18+
}
19+
20+
}
21+
return maxProfit;
22+
}
23+
24+
25+
public static void main(String[] args) {
26+
int [] prices={7,1,5,3,6,4};
27+
System.out.println(buyAndSellStock(prices));
28+
}
29+
}
30+
/* time complexity 0(n) is proportional to n*/

0 commit comments

Comments
 (0)