Best Time to Buy and Sell Stock in Dart — DP Explained

· 4 min read

⚡ TL;DR

Solve LeetCode

Best Time to Buy and Sell Stock (LeetCode #121) is a classic dynamic programming problem: given daily stock prices, find the maximum profit from one buy-sell transaction.

Problem Statement

Given an array prices where prices[i] is the price of a stock on day i, find the maximum profit you can achieve. You can only complete one transaction (buy once, sell once). Note you cannot sell before buying.

Examples:

Copy
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.

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: No profit possible since prices always decrease.

Approach 1: Brute Force (O(n²))

Try every buy-sell pair where buy comes before sell.

Copy
int maxProfitBrute(List<int> prices) {
  int maxProfit = 0;
  int n = prices.length;

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

  return maxProfit;
}

void main() {
  print(maxProfitBrute([7,1,5,3,6,4])); // 5
  print(maxProfitBrute([7,6,4,3,1])); // 0
}

Time: O(n²) — too slow for interviews
Space: O(1)


Approach 2: Single Pass (Optimal)

Track the minimum price seen so far, and update max profit at each step.

Copy
int maxProfit(List<int> prices) {
  if (prices.isEmpty) return 0;

  int minPrice = prices[0];
  int maxProfit = 0;

  for (int i = 1; i < prices.length; i++) {
    // Update minimum price seen so far
    if (prices[i] < minPrice) {
      minPrice = prices[i];
    }
    // Update max profit if selling today gives better profit
    else if (prices[i] - minPrice > maxProfit) {
      maxProfit = prices[i] - minPrice;
    }
  }

  return maxProfit;
}

void main() {
  print(maxProfit([7,1,5,3,6,4])); // 5
  print(maxProfit([7,6,4,3,1])); // 0
  print(maxProfit([2,4,1])); // 2
}

Time: O(n) — single pass
Space: O(1)

How it works:

  • Track lowest price to buy at (minPrice)
  • Calculate profit if selling at current price (prices[i] - minPrice)
  • Update max profit if current profit is higher

Approach 3: Dynamic Programming (Educational)

For conceptual understanding, define DP state:

  • dp[i] = maximum profit achievable by day i
Copy
import 'dart:math';

int maxProfitDP(List<int> prices) {
  if (prices.isEmpty) return 0;

  int n = prices.length;
  List<int> dp = List.filled(n, 0);
  int minPrice = prices[0];

  for (int i = 1; i < n; i++) {
    minPrice = min(minPrice, prices[i]);
    dp[i] = max(dp[i - 1], prices[i] - minPrice);
  }

  return dp[n - 1];
}

void main() {
  print(maxProfitDP([7,1,5,3,6,4])); // 5
}

Time: O(n)
Space: O(n) for DP array — can be optimized to O(1) by tracking only the previous day.


Dart-Specific Tips

  • List.filled(n, 0) creates a fixed-size list
  • min(a, b) and max(a, b) from dart:math return minimum/maximum of two values (remember to import 'dart:math';)
  • Use isEmpty and isNotEmpty instead of length == 0
  • Dart lists are 0-indexed like Python/Java

Complexity Comparison

ApproachTimeSpaceNotes
Brute ForceO(n²)O(1)Rarely accepted in interviews
Single PassO(n)O(1)✅ Best for production code
Dynamic ProgrammingO(n)O(n)Educational, can be optimized to O(1)

Follow-Up Problems

  • Best Time to Buy and Sell Stock II (#122) — unlimited transactions (accumulate all positive slopes)
  • Best Time with Cooldown (#309) — after sell, must skip one day
  • Best Time with Fee (#714) — subtract fee per transaction

Master #121 first — it’s the building block for all harder variants.

FAQ

What is the best approach to solve Best Time to Buy and Sell Stock in Dart?

The recommended approach is the optimal approach, which runs in O(n²) time with O(1) space. The full Dart implementation is shown above.

What is the time complexity of Best Time to Buy and Sell Stock in Dart?

Using the optimal approach, the time complexity is O(n²) and the space complexity is O(1).

Scroll down to load comments...
Related Blogs
Add an MCP Server to Your Flutter/Dart Tooling

Add an MCP Server to Your Flutter/Dart Tooling

Integrate a Model Context Protocol (MCP) server into your Flutter/Dart workflow. Step-by-step setup with Claude Code and real-world use cases.

AI TOOLSMCPFLUTTERDARTDEVELOPER TOOLS

October 06, 2026

All about SOLID Principles in Flutter: Examples and Tips

All about SOLID Principles in Flutter: Examples and Tips

Check out this guide on SOLID principles in Flutter by Mihir Pipermitwala, a software engineer from Surat. Learn with real-world examples!

DARTFLUTTERSOLID PRINCIPLES

April 11, 2023

Related Problems
Maximum Subarray in Dart — Kadane's Algorithm (Optimal) & More

Maximum Subarray in Dart — Kadane's Algorithm (Optimal) & More

Solve Maximum Subarray in Dart with working code. Kadane's Algorithm (Optimal) approach with O(n) time, plus complexity analysis and interview tips.

DART PROGRAMMINGALGORITHMSCODING INTERVIEWDATA STRUCTURES

October 23, 2025

Remove Duplicates from Sorted Array in Dart — Two Pointers & More

Remove Duplicates from Sorted Array in Dart — Two Pointers & More

Solve Remove Duplicates from Sorted Array in Dart with working code. Two Pointers (Optimal) approach with O(n) time, plus complexity analysis and interview tips.

DART PROGRAMMINGALGORITHMSCODING INTERVIEWDATA STRUCTURES

August 29, 2024

Related Recommended Services
Visual Studio Code for the Web

Visual Studio Code for the Web

Build with Visual Studio Code, anywhere, anytime, in your browser.

IDEVISUAL STUDIOVISUAL STUDIO CODEWEB
Renovate | Automated Dependency Updates

Renovate | Automated Dependency Updates

Renovate Bot keeps source code dependencies up-to-date using automated Pull Requests.

AUTOMATED DEPENDENCY UPDATESBUNDLERCOMPOSERGITHUBGO MODULES
Best XML Formatter and XML Beautifier

Best XML Formatter and XML Beautifier

Online XML Formatter will format xml data, helps to validate, and works as XML Converter. Save and Share XML.

XMLXML BEAUTIFIERXML CONVERTERXML FORMATXML FORMATTER
Kubecost | Kubernetes cost monitoring and management

Kubecost | Kubernetes cost monitoring and management

Kubecost started in early 2019 as an open-source tool to give developers visibility into Kubernetes spend. We maintain a deep commitment to building and supporting dedicated solutions for the open source community.

CLOUDKUBECOSTKUBERNETESOPEN SOURCESELF HOSTED
Related Recommended Stories
How GitHub reduced testing time for iOS apps with new runner features

How GitHub reduced testing time for iOS apps with new runner features

Learn how GitHub used macOS and Apple Silicon runners for GitHub Actions to build, test, and deploy our iOS app faster.

IOSGITHUBTESTINGRUNNER
5 ways to transform your workflow using GitHub Copilot and MCP

5 ways to transform your workflow using GitHub Copilot and MCP

Learn how to streamline your development workflow with five different MCP use cases.

AGENT MODECODING AGENTCOPILOTFIGMAGITHUB
One weird trick for powerful Git aliases

One weird trick for powerful Git aliases

Advanced Git Aliases

ALIASALIAS TEMPLATEATLASSIANBITBUCKETGIT
Awesome Python

Awesome Python

An opinionated list of awesome Python frameworks, libraries, software and resources

AWESOMEAWESOME PYTHONCOLLECTIONSGITHUBPYTHON
Related Recommended Tools
Find out what websites are built with - Wappalyzer

Find out what websites are built with - Wappalyzer

Find out the technology stack of any website. Create lists of websites and contacts by the technologies they use.

ADD ONSANALYTICSAPP STOREAPPLEBOOKING
Sourcetree | Free Git GUI for Mac and Windows

Sourcetree | Free Git GUI for Mac and Windows

A Git GUI that offers a visual representation of your repositories. Sourcetree is a free Git client for Windows and Mac.

GITGITHUBGITLABATLASSIANBITBUCKET
Related Recommended Videos