Skip to content

Commit c052ebc

Browse files
committed
stock max price algorithm
1 parent 70551fc commit c052ebc

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

algorithm/stack/Main.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public static void main(String[] args) {
1111
System.out.println("pop "+stack.pop());
1212
// stack.pop();
1313

14-
System.out.println("peek "+stack.peek());
14+
System.out.println("peek "+stack.peek());
1515

1616
stack.show();
1717
}

questions/best_time_to_buy_and_sell_stocks/Main.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
public class Main {
44
public static void main(String[] args) {
5-
5+
int prices[] = {7, 1, 5, 3, 6, 4};
6+
int profit=5;
7+
8+
Problem problem=new Problem();
9+
int output=problem.findMaxProfit(prices);
10+
System.out.println("Max Profit is "+output);
611
}
712
}
Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
11
package questions.best_time_to_buy_and_sell_stocks;
22

33
public class Problem {
4-
4+
public int findMaxProfit(int[] array){
5+
int maxProfit=0;
6+
int lowPrice=array[0];
7+
8+
for (int i = 1; i < array.length; i++) {
9+
if(array[i]<lowPrice){
10+
lowPrice=array[i];
11+
}else if(maxProfit<array[i]-lowPrice){
12+
maxProfit=array[i]-lowPrice;
13+
}
14+
15+
}
16+
return maxProfit;
17+
}
518
}

0 commit comments

Comments
 (0)