-
Notifications
You must be signed in to change notification settings - Fork 0
/
StockProfit.java
47 lines (34 loc) · 1.41 KB
/
StockProfit.java
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
45
import java.util.Arrays;
class StockProfit {
// Function to calculate the maximum profit
static long getMaximumProfit(long[] Arr, int n) {
// Create a 2D array for dynamic programming with dimensions [n+1][2]
long[][] dp = new long[n + 1][2];
// Initialize the entire dp table with -1
for (long[] row : dp) {
Arrays.fill(row, -1);
}
// Base condition: If we have no stocks to buy or sell, profit is 0
dp[n][0] = dp[n][1] = 0;
long profit = 0;
// Iterate through the array in reverse to calculate the maximum profit
for (int ind = n - 1; ind >= 0; ind--) {
for (int buy = 0; buy <= 1; buy++) {
if (buy == 0) { // We can buy the stock
profit = Math.max(0 + dp[ind + 1][0], -Arr[ind] + dp[ind + 1][1]);
}
if (buy == 1) { // We can sell the stock
profit = Math.max(0 + dp[ind + 1][1], Arr[ind] + dp[ind + 1][0]);
}
dp[ind][buy] = profit;
}
}
return dp[0][0]; // The maximum profit is stored at dp[0][0]
}
public static void main(String args[]) {
int n = 6;
long[] Arr = {7, 1, 5, 3, 6, 4};
// Calculate and print the maximum profit
System.out.println("The maximum profit that can be generated is " + getMaximumProfit(Arr, n));
}
}