Best Time to Buy and Sell Stock in Go — Optimal Solution & More

· 3 min read

⚡ TL;DR

Solve Best Time to Buy and Sell Stock in Go with working code. One-Pass Min Tracking (Optimal) approach with O(n) time, plus complexity analysis and interview tips.

Best Time to Buy and Sell Stock (#121 — Easy): Given an array prices where prices[i] is the price of a stock on day i, choose one day to buy and a different later day to sell to maximize profit. Return that maximum profit, or 0 when no profitable trade exists.

Problem Statement

Given an array prices where prices[i] is the price of a stock on day i, choose one day to buy and a different later day to sell to maximize profit. Return that maximum profit, or 0 when no profitable trade exists.

Example:

Copy
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1), sell on day 5 (price = 6), profit = 6 − 1 = 5.

Approach: One-Pass Min Tracking (Optimal)

Time: O(n) | Space: O(1)

Walk the prices once while remembering the cheapest price seen so far. At each day the best possible trade selling today is today’s price minus that minimum, so update the answer on the fly.

Copy
package main

import ("fmt")

func maxProfit(prices []int) int {
	minPrice := prices[0]
	best := 0
	for _, price := range prices[1:] {
		if price < minPrice {
			minPrice = price
		} else if price-minPrice > best {
			best = price - minPrice
		}
	}
	return best
}

func main() {
	fmt.Println(maxProfit([]int{7, 1, 5, 3, 6, 4}))
}

Approach: Brute Force

Time: O(n²) | Space: O(1)

Try every buy-day/sell-day pair, keep the largest positive difference, and return it. Straightforward but quadratic, which fails on large inputs.

Copy
package main

import ("fmt")

func maxProfitBrute(prices []int) int {
	best := 0
	for i := 0; i < len(prices); i++ {
		for j := i + 1; j < len(prices); j++ {
			if prices[j]-prices[i] > best {
				best = prices[j] - prices[i]
			}
		}
	}
	return best
}

func main() {
	fmt.Println(maxProfitBrute([]int{7, 1, 5, 3, 6, 4}))
}

Key Takeaways

  • Start with the brute-force approach to understand the problem
  • One-Pass Min Tracking (Optimal) gives the optimal O(n) solution
  • Practice this pattern — it appears frequently in coding interviews

FAQ

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

The recommended approach is One-Pass Min Tracking (Optimal), which runs in O(n) time with O(1) space. The full Go implementation is shown above.

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

Using One-Pass Min Tracking (Optimal), the time complexity is O(n) and the space complexity is O(1).

Happy coding!

Scroll down to load comments...
Related Problems
Best Time to Buy and Sell Stock in Python

Best Time to Buy and Sell Stock in Python

Solve Best Time to Buy and Sell Stock in Python with working code. One-Pass Min Tracking (Optimal) approach with O(n) time, plus complexity analysis and interview tips.

PYTHONALGORITHMSCODING INTERVIEWDATA STRUCTURES

September 12, 2026

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

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

Solve LeetCode

DARTALGORITHMSCODING INTERVIEWDYNAMIC PROGRAMMING

September 12, 2026

Best Time to Buy and Sell Stock in Swift — Solution & Explanation

Best Time to Buy and Sell Stock in Swift — Solution & Explanation

Solve Best Time to Buy and Sell Stock in Swift with working code. One-Pass Min Tracking (Optimal) approach with O(n) time, plus complexity analysis and interview tips.

SWIFTALGORITHMSCODING INTERVIEWDATA STRUCTURES

September 12, 2026

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

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

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

GOLANGALGORITHMSCODING INTERVIEWDATA STRUCTURES

October 23, 2025

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

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

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

GOLANGALGORITHMSCODING 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