Repository: TheAlgorithms/Java
Pull request #5793 (2024-10-14 04:02:52)

feat: Add `StockProfitCalculator` new algorithm with Junit tests
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5793?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `75.00000%` with `2 lines` in your changes missing coverage. Please review.
> Project coverage is 64.22%. Comparing base [(`213fd5a`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/213fd5a4931ba1cb74fed76ff97043ae34ff174b?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`f9f79cf`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/f9f79cf1b8823363338a64a266cbb3b81879c0d1?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5793?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...rithms/greedyalgorithms/StockProfitCalculator.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5793?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fgreedyalgorithms%2FStockProfitCalculator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9ncmVlZHlhbGdvcml0aG1zL1N0b2NrUHJvZml0Q2FsY3VsYXRvci5qYXZh) | 75.00% | [1 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5793?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5793      +/-   ##
============================================
+ Coverage     64.21%   64.22%   +0.01%     
- Complexity     4216     4219       +3     
============================================
  Files           588      589       +1     
  Lines         16426    16434       +8     
  Branches       3170     3171       +1     
============================================
+ Hits          10548    10555       +7     
- Misses         5448     5449       +1     
  Partials        430      430              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5793?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 64297571..aa34bf1a 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -320,6 +320,7 @@
             * [JobSequencing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java)
             * [MergeIntervals](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/MergeIntervals.java)
             * [MinimizingLateness](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/MinimizingLateness.java)
+            * [StockProfitCalculator](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/StockProfitCalculator.java)
           * io
             * [BufferedReader](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/io/BufferedReader.java)
           * lineclipping
@@ -920,6 +921,7 @@
             * [JobSequencingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java)
             * [MergeIntervalsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/MergeIntervalsTest.java)
             * [MinimizingLatenessTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessTest.java)
+            * [StockProfitCalculatorTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/StockProfitCalculatorTest.java)
           * io
             * [BufferedReaderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/io/BufferedReaderTest.java)
           * lineclipping
diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/StockProfitCalculator.java b/src/main/java/com/thealgorithms/greedyalgorithms/StockProfitCalculator.java
new file mode 100644
index 00000000..01950d90
--- /dev/null
+++ b/src/main/java/com/thealgorithms/greedyalgorithms/StockProfitCalculator.java
@@ -0,0 +1,34 @@
+package com.thealgorithms.greedyalgorithms;
+
+/**
+ * The StockProfitCalculator class provides a method to calculate the maximum profit
+ * that can be made from a single buy and sell of one share of stock.
+ * The approach uses a greedy algorithm to efficiently determine the maximum profit.
+ *
+ * @author Hardvan
+ */
+public final class StockProfitCalculator {
+    private StockProfitCalculator() {
+    }
+
+    /**
+     * Calculates the maximum profit from a list of stock prices.
+     *
+     * @param prices an array of integers representing the stock prices on different days
+     * @return the maximum profit that can be achieved from a single buy and sell
+     * transaction, or 0 if no profit can be made
+     */
+    public static int maxProfit(int[] prices) {
+        if (prices == null || prices.length == 0) {
+            return 0;
+        }
+
+        int minPrice = prices[0];
+        int maxProfit = 0;
+        for (int price : prices) {
+            minPrice = Math.min(price, minPrice);
+            maxProfit = Math.max(price - minPrice, maxProfit);
+        }
+        return maxProfit;
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/StockProfitCalculatorTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/StockProfitCalculatorTest.java
new file mode 100644
index 00000000..afad76a3
--- /dev/null
+++ b/src/test/java/com/thealgorithms/greedyalgorithms/StockProfitCalculatorTest.java
@@ -0,0 +1,21 @@
+package com.thealgorithms.greedyalgorithms;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class StockProfitCalculatorTest {
+
+    @ParameterizedTest
+    @MethodSource("provideTestCases")
+    public void testMaxProfit(int[] prices, int expected) {
+        assertEquals(expected, StockProfitCalculator.maxProfit(prices));
+    }
+
+    private static Stream<Arguments> provideTestCases() {
+        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));
+    }
+}