coding-interview|July 06, 2021|2 min read

Leetcode Solution - Best Time to Buy and Sell Stock

TL;DR

Track the minimum price seen so far and the maximum profit at each step. One pass, O(n) time, O(1) space.

Leetcode Solution - Best Time to Buy and Sell Stock

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.

Brute Force - O(n^2)

public int maxProfit(int[] prices) {
  int l=prices.length;
  int maxProfit = 0;

  for(int i=0; i<l-1; i++) {
    for(int j=i+1; j<l; j++) {
      int diff = prices[j] - prices[i];
      if (diff > maxProfit) {
        maxProfit = diff;
      }
    }
  }
  
  return maxProfit;
}

Better Solution - O(n)

WWe can keep a track of minimum price as we iterate. And, calculate the profit till now. And we can also keep track of maximum profit so far.

The code is pretty simple.

public int maxProfit(int[] prices) {
  int l=prices.length;

  int maxProfit = 0;
  int minPrice = prices[0];
  for(int i=1; i<l; i++) {
    maxProfit = Math.max(maxProfit, prices[i]-minPrice);
    minPrice = Math.min(minPrice, prices[i]);
  }

  return maxProfit;
}

Related Posts

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Longest Common Prefix - Leet Code Solution

Longest Common Prefix - Leet Code Solution

Problem Statement Write a function to find the longest common prefix string…

First Unique Character in a String - Leet Code Solution

First Unique Character in a String - Leet Code Solution

Problem Statement Given a string, find the first non-repeating character in it…

Remove Duplicates from Sorted Array - Leet Code Solution

Remove Duplicates from Sorted Array - Leet Code Solution

Problem Statement Given a sorted array nums, remove the duplicates in-place such…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Find the maximum sum of any continuous subarray of size K

Find the maximum sum of any continuous subarray of size K

Introduction You are given an array of integers with size N, and a number K…

Latest Posts

System Design Patterns for Scaling Writes

System Design Patterns for Scaling Writes

In the companion article on scaling reads, we covered caching, replicas, and…

Serverless vs Containers — The Decision I Keep Revisiting

Serverless vs Containers — The Decision I Keep Revisiting

Every time I start a new service, I have the same argument with myself. Lambda…

System Design Patterns for Scaling Reads

System Design Patterns for Scaling Reads

Most production systems are read-heavy. A typical web application sees 90-9…

Building a Production RAG Pipeline — From Chunking to Retrieval to Generation

Building a Production RAG Pipeline — From Chunking to Retrieval to Generation

Large Language Models are powerful, but they hallucinate. They confidently make…

Prompt Engineering Patterns That Actually Work in Production

Prompt Engineering Patterns That Actually Work in Production

Most prompt engineering advice on the internet is useless in production. “Be…

Jenkins Pipeline with Jenkinsfile - How To Schedule Job on Cron and Not on Code Commit

Jenkins Pipeline with Jenkinsfile - How To Schedule Job on Cron and Not on Code Commit

Introduction In this post we will see following: How to schedule a job on cron…