Skip to content

Commit b566655

Browse files
committed
feat: Add StockProfitCalculator new algorithm with Junit tests
1 parent 213fd5a commit b566655

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
/**
4+
* The StockProfitCalculator class provides a method to calculate the maximum profit
5+
* that can be made from a single buy and sell of one share of stock.
6+
* The approach uses a greedy algorithm to efficiently determine the maximum profit.
7+
*
8+
* @author Hardvan
9+
*/
10+
public class StockProfitCalculator {
11+
12+
/**
13+
* Calculates the maximum profit from a list of stock prices.
14+
*
15+
* @param prices an array of integers representing the stock prices on different days
16+
* @return the maximum profit that can be achieved from a single buy and sell
17+
* transaction, or 0 if no profit can be made
18+
*/
19+
public static int maxProfit(int[] prices) {
20+
if (prices == null || prices.length == 0) {
21+
return 0;
22+
}
23+
24+
int minPrice = prices[0];
25+
int maxProfit = 0;
26+
for (int price : prices) {
27+
minPrice = Math.min(price, minPrice);
28+
maxProfit = Math.max(price - minPrice, maxProfit);
29+
}
30+
return maxProfit;
31+
}
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.stream.Stream;
6+
import org.junit.jupiter.params.ParameterizedTest;
7+
import org.junit.jupiter.params.provider.Arguments;
8+
import org.junit.jupiter.params.provider.MethodSource;
9+
10+
public class StockProfitCalculatorTest {
11+
12+
@ParameterizedTest
13+
@MethodSource("provideTestCases")
14+
public void testMaxProfit(int[] prices, int expected) {
15+
assertEquals(expected, StockProfitCalculator.maxProfit(prices));
16+
}
17+
18+
private static Stream<Arguments> provideTestCases() {
19+
return Stream.of(Arguments.of(new int[] {7, 1, 5, 3, 6, 4}, 5), Arguments.of(new int[] {7, 6, 4, 3, 1}, 0), Arguments.of(new int[] {5, 5, 5, 5, 5}, 0), Arguments.of(new int[] {10}, 0), Arguments.of(new int[] {1, 5}, 4), Arguments.of(new int[] {2, 4, 1, 3, 7, 5}, 6));
20+
}
21+
}

0 commit comments

Comments
 (0)