forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbestTimeToBuyAndSellStock
82 lines (68 loc) · 2.33 KB
/
bestTimeToBuyAndSellStock
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
public class bestTimeToBuyAndSellStock2 {
// driver code
public static void main(String[] args) {
int[] Arr = {7, 1, 5, 3, 6, 4};
System.out.println(maxProfit_start(Arr));
}
static int maxProfit_start(int[] prices) {
int n = prices.length;
int[][] dp = new int[n][2];
for (int[] row : dp) {
Arrays.fill(row, -1);
}
return maxprofit(0, 0, n, prices,dp);
}
//recursion
static int maxprofit(int ind, int buy, int n, int[] prices) {
if (ind == n) return 0;
int profit = 0;
// we can by the stock
if (buy == 0) {
profit = Math.max(0 + maxprofit(ind + 1, 0, n, prices), maxprofit(ind + 1, 1, n, prices) - prices[ind]);
}
if (buy == 1) {
// we can sell the stock
profit = Math.max(0 + maxprofit(ind + 1, 1, n, prices), maxprofit(ind + 1, 0, n, prices) + prices[ind]);
}
return profit;
}
// memorazation
static int maxprofit(int ind, int buy, int n, int[] prices, int[][] dp) {
if (ind == n) return 0;
if (dp[ind][buy] != -1) return dp[ind][buy];
int profit = 0;
// we can by the stock
if (buy == 0) {
profit = Math.max(0 + maxprofit(ind + 1, 0, n, prices), maxprofit(ind + 1, 1, n, prices) - prices[ind]);
}
if (buy == 1) {
// we can sell the stock
profit = Math.max(0 + maxprofit(ind + 1, 1, n, prices), maxprofit(ind + 1, 0, n, prices) + prices[ind]);
}
return dp[ind][buy] = profit;
}
}
// Tabulation
public int maxProfit(int[] prices){
int n = prices.length;
int dp[][] = new int[n+1][2];
for (int row[]:dp){
Arrays.fill(row,-1);
}
//base condation
dp[n][0] = dp[n][1] = 0;
int profit = 0 ;
for (int ind = n-1; ind >=0 ; ind--) {
for (int buy = 0; buy <=1 ; buy++) {
if (buy == 0){
// we can buy stock
profit = Math.max(0+dp[ind+1][0],dp[ind+1][1] -prices[ind]);
}
if (buy ==1 ){
profit = Math.max(0+dp[ind+1][1],dp[ind+1][0] +prices[ind]);
}
dp[ind][buy] = profit;
}
}
return dp[0][0];
}