-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStockProfitCalculator.java
More file actions
44 lines (31 loc) · 1018 Bytes
/
StockProfitCalculator.java
File metadata and controls
44 lines (31 loc) · 1018 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
42
43
44
package com.sarvesh.javabasics;
import java.util.Scanner;
public class StockProfitCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of Days: ");
int n = sc.nextInt();
int[] prices = new int[n];
System.out.print("Enter Stock Prices:");
for (int i = 0; i < n; i++) {
prices[i] = sc.nextInt();
}
System.out.println("Maximum Profit: " + maximumProfit(prices));
sc.close();
}
public static int maximumProfit(int[] prices) {
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else {
int profit = prices[i] - minPrice;
if (profit > maxProfit) {
maxProfit = profit;
}
}
}
return maxProfit;
}
}