-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuySellStock.java
More file actions
41 lines (29 loc) · 888 Bytes
/
BuySellStock.java
File metadata and controls
41 lines (29 loc) · 888 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.vinay.practice.lc;
public class BuySellStock {
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = {7,1,5,3,6,4};
System.out.println(maxProfit(arr));
}
public static int maxProfit(int[] prices) {
int maxProfit = 0;
/*
for (int i=0;i<prices.length; i++){
for(int j=i+1; j<prices.length; j++){
if(j>i && prices[j]-prices[i] > diff){
maxProfit = prices[j] - prices[i];
}
}
}
*/
int minPrice = Integer.MAX_VALUE;
for(int i=0; i<prices.length; i++){
if(prices[i] < minPrice){
minPrice = prices[i];
} else if(prices[i] - minPrice > maxProfit){
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
}