Перейти к содержанию

Best Time to Buy and Sell Stock

🇷🇺 Название: Лучшее время для покупки и продажи акций
LeetCode: best-time-to-buy-and-sell-stock
Временная сложность: O(n)
Пространственная сложность: O(1)

Решение

from typing import List


class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        buy_price = prices[0]
        profit = 0

        for price in prices[1:]:
            if buy_price > price:
                buy_price = price

            profit = max(profit, price - buy_price)

        return profit

🇺🇸 Условие

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

🇷🇺 Условие

Примеры

Example 1:

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.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

{
  "examples": [
    {
      "input": {
        "prices": [7,1,5,3,6,4]
      },
      "output": 5
    },
    {
      "input": {
        "prices": [7,6,4,3,1]
      },
      "output": 0
    }
  ]
}

Ограничения

  • \(1 \leq prices.length \leq 10^5\)
  • \(0 \leq prices[i] \leq 10^4\)

Потребление ресурсов

⏱ Time complexity: O(n)

  • Один проход по prices длины n
  • Все операции внутри цикла — O(1)

Итог: O(n)

🧠 Space complexity: O(1)

  • Используются только 2 переменные (buy_price, profit)
  • Память не зависит от входных данных

Итог: O(1)

easy array dynamic-programming


Metadata

  • title_rus: Лучшее время для покупки и продажи акций
  • difficulty: Easy
  • leetcode_url: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
  • topics: ['Array', 'Dynamic Programming']
  • time: O(n)
  • space: O(1)
  • grind75: True
  • tags: ['Array', 'Dynamic Programming', 'Easy', 'problem']
  • git_revision_date_localized: 5 июля 2025 г.
  • git_revision_date_localized_hash: f6ac458ea7f3485fe36c4b8c8f7c610ae2d995e7
  • git_revision_date_localized_tag:
  • git_revision_date_localized_raw_date: 5 июля 2025 г.
  • git_revision_date_localized_raw_datetime: 5 июля 2025 г. 19:32:08
  • git_revision_date_localized_raw_datetime-timezone: 5 июля 2025 г. 19:32:08 UTC
  • git_revision_date_localized_raw_iso_date: 2025-07-05
  • git_revision_date_localized_raw_iso_datetime: 2025-07-05 19:32:08
  • git_revision_date_localized_raw_timeago:
  • git_revision_date_localized_raw_custom: 05. июля 2025
  • git_site_revision_date_localized_hash: f6ac458ea7f3485fe36c4b8c8f7c610ae2d995e7
  • git_site_revision_date_localized_tag:
  • git_site_revision_date_localized: 5 июля 2025 г.
  • git_site_revision_date_localized_raw_date: 5 июля 2025 г.
  • git_site_revision_date_localized_raw_datetime: 5 июля 2025 г. 19:32:08
  • git_site_revision_date_localized_raw_datetime-timezone: 5 июля 2025 г. 19:32:08 UTC
  • git_site_revision_date_localized_raw_iso_date: 2025-07-05
  • git_site_revision_date_localized_raw_iso_datetime: 2025-07-05 19:32:08
  • git_site_revision_date_localized_raw_timeago:
  • git_site_revision_date_localized_raw_custom: 05. июля 2025