TGViewer
PHP | LeetCode PHP | LeetCode @easy_php_task · 1.33K subscribers
Post #822 190
Задача: 121. Best Time to Buy and Sell Stock
Сложность: easy

Вам дан массив цен, где prices[i] является ценой данной акции в i-й день.

Ваша задача — максимизировать вашу прибыль, выбрав один день для покупки акции и другой день в будущем для ее продажи.

Верните максимальную прибыль, которую вы можете получить от этой операции. Если прибыль получить невозможно, верните 0.

Пример:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.


👨‍💻 Алгоритм:

1⃣Инициализируем minPrice значением PHP_INT_MAX, maxProfit — 0.

2⃣Проходим по всем ценам:
Если текущая цена меньше minPrice, обновляем minPrice.
Если текущая прибыль (price - minPrice) больше maxProfit, обновляем maxProfit.

3⃣Возвращаем maxProfit.

😎 Решение:
class Solution {
public function maxProfit($prices) {
$minPrice = PHP_INT_MAX;
$maxProfit = 0;
foreach ($prices as $price) {
if ($price < $minPrice) {
$minPrice = $price;
} elseif ($price - $minPrice > $maxProfit) {
$maxProfit = $price - $minPrice;
}
}
return $maxProfit;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_php_task
  1. Oct 17, 2026Задача: 1302. Deepest Leaves Sum Сложность: medium Дано корень бинарного дерева, вернуть с…
  2. Oct 16, 2026Задача: 760. Find Anagram Mappings Сложность: easy Вам даны два целочисленных массива nums…
  3. Oct 15, 2026Задача: 474. Ones and Zeroes Сложность: medium Дан массив двоичных строк strs и два целых…
  4. Oct 15, 2026Задача: 1273. Delete Tree Nodes Сложность: medium Дерево, укорененное в узле 0, задано сле…
  5. Oct 14, 2026Задача: 724. Find Pivot Index Сложность: easy Если задан массив целых чисел nums, вычислит…
  6. Oct 14, 2026Задача: 674. Longest Continuous Increasing Subsequence Сложность: easy Дан неотсортированн…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →