Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Best Time to Buy and Sell Stock

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "121" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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. Constraints: 1 <= prices.length <= 105 0 <= prices[i] <= 104

Explanation

Here's the breakdown of the optimal solution:

  • Key Idea: Iterate through the prices array, keeping track of the minimum price encountered so far. The maximum profit is calculated as the difference between the current price and the minimum price.
  • Optimization: Update the minimum price as you traverse the array. The maximum profit is continuously updated whenever a larger profit is found.
  • No Profit: If the maximum profit remains 0 after traversing the entire array, it means no profitable transaction is possible, and 0 is returned.

  • Complexity: O(n) runtime, O(1) storage

Code

    def maxProfit(prices):
    """
    Calculates the maximum profit that can be made by buying and selling a stock once.

    Args:
        prices: A list of stock prices for each day.

    Returns:
        The maximum profit that can be made, or 0 if no profit is possible.
    """
    min_price = float('inf')  # Initialize with a very large number
    max_profit = 0

    for price in prices:
        if price < min_price:
            min_price = price
        else:
            profit = price - min_price
            if profit > max_profit:
                max_profit = profit

    return max_profit

More from this blog

C

Chatmagic blog

2894 posts