-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBestDayToBuyAndSellStocks.java
More file actions
32 lines (28 loc) · 1.01 KB
/
BestDayToBuyAndSellStocks.java
File metadata and controls
32 lines (28 loc) · 1.01 KB
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
import java.util.LinkedHashMap;
import java.util.Scanner;
public class BestDayToBuyAndSellStocks {
public static void main(String[] args) {
try(Scanner sc = new Scanner(System.in)){ //preventing leak of resource with try-with-resource.
String [] weekdays = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
LinkedHashMap <String, Integer> stocks = new LinkedHashMap<>();
for(String w:weekdays) {
System.out.println("Enter the price of stocks for "+w);
stocks.put(w,sc.nextInt());
}
System.out.println(stocks);
int stockdiff=0;
String buy=null;
String sell=null;
for(int i =0;i<stocks.size()-1;i++) {
if(stocks.get(weekdays[i+1])-stocks.get(weekdays[i])>0&&stocks.get(weekdays[i+1])-stocks.get(weekdays[i])>stockdiff) {
stockdiff=stocks.get(weekdays[i+1])-stocks.get(weekdays[i]);
buy=weekdays[i];
sell=weekdays[i+1];
}
}
System.out.println("Buy on: "+buy+"\nSell on:"+sell+"\nProfit: "+stockdiff);
} catch(Exception e) {
e.printStackTrace();
}
}
}