yangyi 2 недель назад
Родитель
Сommit
a9e3521531
2 измененных файлов с 66 добавлено и 0 удалено
  1. 24 0
      src/leetcode/p121/Solution.java
  2. 42 0
      src/leetcode/p121/SolutionTest.java

+ 24 - 0
src/leetcode/p121/Solution.java

@@ -0,0 +1,24 @@
+package leetcode.p121;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/23 22:46
+ * @Description: https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/description/
+ * 121. 买卖股票的最佳时机
+ */
+public class Solution {
+    public int maxProfit(int[] prices) {
+        /**
+         * 维护当前最小值,用当前值减去当前最小值就是当前最大值
+         */
+        int min = prices[0];
+        int max = 0;
+        for (int i = 1; i < prices.length; i++) {
+            max = Math.max(max, prices[i] - min);
+            min = Math.min(min, prices[i]);
+        }
+        return max;
+    }
+}

+ 42 - 0
src/leetcode/p121/SolutionTest.java

@@ -0,0 +1,42 @@
+package leetcode.p121;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2026/3/23 22:49
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private int[] prices;
+    private int expected;
+
+    public SolutionTest(int[] prices, int expected) {
+        this.prices = prices;
+        this.expected = expected;
+    }
+    @Parameterized.Parameters
+    public static Collection<Object[]> data(){
+        return Arrays.asList(new Object[][]{
+                {new int[]{7,1,5,3,6,4},5},
+                {new int[]{7,6,4,3,1},0},
+        });
+    }
+
+
+    @Test
+    public void maxProfit() {
+        assertEquals(expected,solution.maxProfit(prices));
+    }
+}