Skip to content

Commit c2a126b

Browse files
Merge pull request Pradeepsingh61#493 from FirdausJawed/firdaus
Buy and sell stock code in java (all variations)
2 parents 89f1123 + d3fd423 commit c2a126b

6 files changed

Lines changed: 495 additions & 0 deletions

File tree

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
Best Time to Buy and Sell Stock with Cooldown
3+
4+
Algorithm Description:
5+
This algorithm finds the maximum profit from buying and selling stocks with as many transactions as you like, but with a cooldown of one day after each sale. You cannot buy a stock on the day immediately after selling it. The approach uses dynamic programming with memoization to avoid redundant calculations. The state is defined by the current day and whether you can buy or must sell. At each step, you decide to buy, sell, or skip, and recursively compute the best outcome.
6+
7+
Use Cases:
8+
- Stock trading with cooldown restrictions (e.g., to avoid rapid trading penalties)
9+
- Any scenario where actions are limited by a cooldown period
10+
11+
Time Complexity: O(n)
12+
- Each state (day, buy/sell) is computed once, and there are 2*n states.
13+
14+
Space Complexity: O(n)
15+
- The DP table stores results for each day and buy/sell state.
16+
*/
17+
18+
package Java.dynamic_programming.BuyAndSellStocks;
19+
20+
import java.util.Arrays;
21+
22+
public class BestTimeToBuyAndSellStockWithCooldown {
23+
public static void main(String[] args) {
24+
BestTimeToBuyAndSellStockWithCooldown bss = new BestTimeToBuyAndSellStockWithCooldown();
25+
int[] a = {1,2,3,0,2};
26+
System.out.println(bss.maxProfit(a)); // Output: 3
27+
28+
// Additional test cases
29+
System.out.println(bss.maxProfit(new int[]{1})); // Output: 0 (edge case: only one day)
30+
System.out.println(bss.maxProfit(new int[]{2,1,4})); // Output: 3
31+
System.out.println(bss.maxProfit(new int[]{})); // Output: 0 (edge case: empty array)
32+
}
33+
34+
/**
35+
* Recursive helper function to calculate max profit with cooldown.
36+
* @param i Current day index
37+
* @param buy 1 if we can buy, 0 if we must sell
38+
* @param a Prices array
39+
* @param dp Memoization table
40+
* @return Maximum profit from day i with given state
41+
*/
42+
private int f(int i, int buy, int[] a, int[][] dp) {
43+
// Base case: If we've reached the end, no more profit can be made
44+
if(i >= a.length){
45+
return 0;
46+
}
47+
// Return cached result if already computed
48+
if(dp[i][buy] != -1){
49+
return dp[i][buy];
50+
}
51+
int profit = 0;
52+
if(buy == 1){
53+
// Option 1: Buy at current day, move to next day with buy=0 (must sell next)
54+
// Option 2: Skip buying, move to next day with buy=1 (still can buy)
55+
profit = Math.max(f(i+1,0,a,dp)-a[i], f(i+1,1,a,dp));
56+
}
57+
else{
58+
// Option 1: Sell at current day, move to day after next (cooldown), can buy again
59+
// Option 2: Skip selling, move to next day with buy=0 (still holding)
60+
profit = Math.max(f(i+2, 1, a, dp) + a[i], f(i+1,0,a,dp));
61+
}
62+
// Store result in dp table and return
63+
return dp[i][buy] = profit;
64+
}
65+
66+
/**
67+
* Calculates the maximum profit with cooldown after selling.
68+
* @param a Prices array
69+
* @return Maximum profit
70+
*/
71+
public int maxProfit(int[] a) {
72+
int n = a.length;
73+
// dp[i][buy]: Max profit at day i, buy/sell state
74+
int[][] dp = new int[n+1][3];
75+
76+
// Initialize dp table with -1 (uncomputed)
77+
for(int[] r: dp) {
78+
Arrays.fill(r,-1);
79+
}
80+
81+
// Start from day 0, can buy
82+
return f(0,1,a,dp);
83+
}
84+
}
85+
86+
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/*
2+
Best Time to Buy and Sell Stock with Transaction Fee
3+
4+
Algorithm Description:
5+
This algorithm computes the maximum profit from buying and selling stocks with as many transactions as you like, but each transaction (buy+sell) incurs a fixed fee. The approach uses dynamic programming with memoization. The state is defined by the current day and whether you can buy or must sell. At each step, you decide to buy, sell (paying the fee), or skip, and recursively compute the best outcome.
6+
7+
Use Cases:
8+
- Stock trading where each transaction incurs a brokerage or transaction fee
9+
- Any scenario where actions have a fixed cost per transaction
10+
11+
Time Complexity: O(n)
12+
- Each state (day, buy/sell) is computed once, and there are 2*n states.
13+
14+
Space Complexity: O(n)
15+
- The DP table stores results for each day and buy/sell state.
16+
*/
17+
18+
package Java.dynamic_programming.BuyAndSellStocks;
19+
20+
import java.util.Arrays;
21+
22+
public class BestTimeToBuyAndSellStockWithTransactionFee {
23+
public static void main(String[] args) {
24+
BestTimeToBuyAndSellStockWithTransactionFee bss = new BestTimeToBuyAndSellStockWithTransactionFee();
25+
int[] a = {1,3,2,8,4,9};
26+
int fee = 2;
27+
System.out.println(bss.maxProfit(a,fee)); // Output: 8
28+
29+
// Additional test cases
30+
System.out.println(bss.maxProfit(new int[]{1,3,7,5,10,3}, 3)); // Output: 6
31+
System.out.println(bss.maxProfit(new int[]{1}, 1)); // Output: 0 (edge case: only one day)
32+
System.out.println(bss.maxProfit(new int[]{}, 1)); // Output: 0 (edge case: empty array)
33+
}
34+
35+
/**
36+
* Recursive helper function to calculate max profit with transaction fee.
37+
* @param i Current day index
38+
* @param buy 1 if we can buy, 0 if we must sell
39+
* @param fee Transaction fee per transaction
40+
* @param a Prices array
41+
* @param dp Memoization table
42+
* @return Maximum profit from day i with given state
43+
*/
44+
private int f(int i, int buy, int fee, int[] a, int[][] dp) {
45+
// Base case: If we've reached the end, no more profit can be made
46+
if(i>=a.length){
47+
return 0;
48+
}
49+
// Return cached result if already computed
50+
if(dp[i][buy] != -1){
51+
return dp[i][buy];
52+
}
53+
54+
int profit = 0;
55+
if(buy == 1) {
56+
// Option 1: Buy at current day, move to next day with buy=0 (must sell next)
57+
// Option 2: Skip buying, move to next day with buy=1 (still can buy)
58+
profit = Math.max(f(i+1,0,fee,a,dp)-a[i] , f(i+1,1,fee,a,dp));
59+
}
60+
else {
61+
// Option 1: Sell at current day, pay fee, move to next day with buy=1 (can buy again)
62+
// Option 2: Skip selling, move to next day with buy=0 (still holding)
63+
profit = Math.max(f(i+1,1,fee,a,dp)+a[i]-fee , f(i+1,0,fee,a,dp));
64+
}
65+
// Store result in dp table and return
66+
return dp[i][buy] = profit;
67+
}
68+
69+
/**
70+
* Calculates the maximum profit with unlimited transactions and a transaction fee.
71+
* @param a Prices array
72+
* @param fee Transaction fee per transaction
73+
* @return Maximum profit
74+
*/
75+
public int maxProfit(int[] a, int fee) {
76+
int n = a.length;
77+
// dp[i][buy]: Max profit at day i, buy/sell state
78+
int[][] dp = new int[n+1][3];
79+
// Initialize dp table with -1 (uncomputed)
80+
for(int[] r : dp){
81+
Arrays.fill(r,-1);
82+
}
83+
// Start from day 0, can buy
84+
return f(0,1,fee,a,dp);
85+
}
86+
}
87+
88+
89+
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Best Time to Buy and Sell Stock I
3+
4+
Algorithm Description:
5+
This algorithm finds the maximum profit from a single buy and sell transaction. It iterates through the price array, tracking the minimum price seen so far and the maximum profit achievable by selling at the current price. The approach is greedy and uses only constant space.
6+
7+
Use Cases:
8+
- Finding the best single buy/sell opportunity in a stock price history
9+
- Any scenario where only one transaction is allowed
10+
11+
Time Complexity: O(n)
12+
- Single pass through the array.
13+
14+
Space Complexity: O(1)
15+
- Only a few variables are used.
16+
*/
17+
18+
package Java.dynamic_programming.BuyAndSellStocks;
19+
20+
class BuyAndSellStock1 {
21+
public static void main(String[] args) {
22+
BuyAndSellStock1 bss = new BuyAndSellStock1();
23+
int[] a = {7,1,5,3,6,4};
24+
System.out.println(bss.maxProfit(a)); // Output: 5
25+
26+
// Additional test cases
27+
System.out.println(bss.maxProfit(new int[]{7,6,4,3,1})); // Output: 0 (no profit possible)
28+
System.out.println(bss.maxProfit(new int[]{1,2})); // Output: 1
29+
System.out.println(bss.maxProfit(new int[]{})); // Output: 0 (edge case: empty array)
30+
}
31+
32+
/**
33+
* Calculates the maximum profit from a single buy and sell transaction.
34+
* @param a Prices array
35+
* @return Maximum profit (0 if no profit is possible)
36+
*/
37+
public int maxProfit(int[] a) {
38+
if (a == null || a.length == 0) return 0;
39+
int n = a.length;
40+
int profit = Integer.MIN_VALUE; // Tracks the maximum profit found so far
41+
int previousStock = a[0]; // Tracks the minimum price seen so far (best day to buy)
42+
43+
// Iterate through each day, starting from the second day
44+
for(int i = 1; i < n; i++) {
45+
int currProfit = a[i] - previousStock; // Profit if bought at previousStock and sold today
46+
profit = Math.max(profit, currProfit); // Update max profit if current is better
47+
previousStock = Math.min(previousStock, a[i]); // Update min price if current is lower
48+
}
49+
// If profit is negative or zero, return 0 (no profit possible)
50+
return profit > 0 ? profit : 0;
51+
}
52+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
Best Time to Buy and Sell Stock II
3+
4+
Algorithm Description:
5+
This algorithm finds the maximum profit from as many buy and sell transactions as you like, but you can only hold one stock at a time. The approach uses dynamic programming with memoization, where the state is defined by the current day and whether you are holding a stock. At each step, you decide to buy, sell, or skip, and recursively compute the best outcome.
6+
7+
Use Cases:
8+
- Stock trading with unlimited transactions, but only one stock can be held at a time
9+
- Any scenario where you want to maximize profit with multiple transactions
10+
11+
Time Complexity: O(n)
12+
- Each state (day, buy/sell) is computed once, and there are 2*n states.
13+
14+
Space Complexity: O(n)
15+
- The DP table stores results for each day and buy/sell state.
16+
*/
17+
18+
package Java.dynamic_programming.BuyAndSellStocks;
19+
20+
import java.util.Arrays;
21+
22+
class BuyAndSellStock2 {
23+
public static void main(String[] args) {
24+
BuyAndSellStock2 bss = new BuyAndSellStock2();
25+
int[] a = {7,1,5,3,6,4};
26+
System.out.println(bss.maxProfit(a)); // Output: 7
27+
28+
// Additional test cases
29+
System.out.println(bss.maxProfit(new int[]{1,2,3,4,5})); // Output: 4
30+
System.out.println(bss.maxProfit(new int[]{7,6,4,3,1})); // Output: 0
31+
System.out.println(bss.maxProfit(new int[]{})); // Output: 0 (edge case: empty array)
32+
}
33+
34+
/**
35+
* Recursive helper function to calculate max profit.
36+
* @param i Current day index
37+
* @param buy 1 if we can sell (currently holding), 0 if we can buy (not holding)
38+
* @param a Prices array
39+
* @param dp Memoization table
40+
* @return Maximum profit from day i with given state
41+
*/
42+
private int f(int i, int buy, int[] a, int[][] dp) {
43+
// Base case: If we've reached the end, no more profit can be made
44+
if(i == a.length){
45+
return 0;
46+
}
47+
// Return cached result if already computed
48+
if(dp[i][buy] != -1){
49+
return dp[i][buy];
50+
}
51+
52+
int profit = 0;
53+
if(buy == 1) {
54+
// Option 1: Sell at current day, move to next day with buy=0 (can buy again)
55+
// Option 2: Skip selling, move to next day with buy=1 (still holding)
56+
profit = Math.max(f(i+1,0,a,dp)+a[i], f(i+1,1,a,dp));
57+
}
58+
else{
59+
// Option 1: Buy at current day, move to next day with buy=1 (must sell next)
60+
// Option 2: Skip buying, move to next day with buy=0 (still not holding)
61+
profit = Math.max(f(i+1,1,a,dp)-a[i], f(i+1,0,a,dp));
62+
}
63+
// Store result in dp table and return
64+
return dp[i][buy] = profit;
65+
}
66+
67+
/**
68+
* Calculates the maximum profit with unlimited transactions.
69+
* @param a Prices array
70+
* @return Maximum profit
71+
*/
72+
public int maxProfit(int[] a) {
73+
int n = a.length;
74+
// dp[i][buy]: Max profit at day i, buy/sell state
75+
int[][] dp = new int[n][3];
76+
77+
// Initialize dp table with -1 (uncomputed)
78+
for(int[] r:dp){
79+
Arrays.fill(r,-1);
80+
}
81+
82+
// Start from day 0, not holding any stock (can buy)
83+
return f(0,0,a,dp);
84+
}
85+
}

0 commit comments

Comments
 (0)