📖 Scenario: You are helping a friend who wants to analyze stock prices over several days to find the best times to buy and sell stocks for maximum profit.They have a list of daily stock prices and want to understand how to find the best single buy-sell pair to maximize profit.
🎯 Goal: Build a Go program that finds the maximum profit possible from buying and selling a stock once, given daily prices.This will teach you how to track minimum prices and calculate profits step-by-step.
📋 What You'll Learn
Create a slice called prices with the exact values: 7, 1, 5, 3, 6, 4
Create an integer variable called minPrice and set it to the first price in prices
Create an integer variable called maxProfit and set it to 0
Use a for loop with index i starting from 1 to iterate over prices
Inside the loop, update minPrice if the current price is lower
Calculate the profit by subtracting minPrice from the current price
Update maxProfit if the calculated profit is higher
Print the maxProfit at the end
💡 Why This Matters
🌍 Real World
Stock traders and investors use similar logic to decide the best times to buy and sell stocks to maximize profit.
💼 Career
Understanding how to analyze sequences of data and find optimal points is useful in finance, data analysis, and software development.
Progress0 / 4 steps
1
Create the stock prices slice
Create a slice called prices with the exact values 7, 1, 5, 3, 6, 4
DSA Go
Hint
Use prices := []int{7, 1, 5, 3, 6, 4} to create the slice.
2
Initialize minPrice and maxProfit variables
Create an integer variable called minPrice and set it to the first element of prices. Then create an integer variable called maxProfit and set it to 0
DSA Go
Hint
Set minPrice to prices[0] and maxProfit to 0.
3
Loop through prices to find max profit
Use a for loop with index i starting from 1 to iterate over prices. Inside the loop, update minPrice if prices[i] is less than minPrice. Calculate the profit by subtracting minPrice from prices[i]. Update maxProfit if the profit is greater than maxProfit
DSA Go
Hint
Use a for loop from 1 to len(prices). Update minPrice and maxProfit inside the loop.
4
Print the maximum profit
Print the value of maxProfit using fmt.Println(maxProfit)
DSA Go
Hint
Use fmt.Println(maxProfit) to print the result.
Practice
(1/5)
1. What is the main goal when solving the Buy and Sell Stocks problem variants?
easy
A. Find the day with the highest stock price only
B. Minimize the number of transactions regardless of profit
C. Maximize the profit by choosing the best days to buy and sell stocks
D. Calculate the average stock price over all days
Solution
Step 1: Understand the problem goal
The problem asks to maximize profit by buying and selling stocks on certain days.
Step 2: Identify the correct objective
Maximizing profit means choosing days to buy low and sell high, not just counting transactions or prices.
Final Answer:
Maximize the profit by choosing the best days to buy and sell stocks -> Option C
Quick Check:
Goal = Maximize profit [OK]
Hint: Focus on profit maximization, not just prices or counts [OK]
Common Mistakes:
Confusing profit with number of transactions
Thinking only about highest price day
Ignoring the buy day in calculations
2. Which of the following Go code snippets correctly initializes a slice to store stock prices for 5 days?
easy
A. prices := []int{7, 1, 5, 3, 6}
B. prices := [5]int{7, 1, 5, 3, 6}
C. prices := make([]int, 5, 5)
D. prices := new([]int{7, 1, 5, 3, 6})
Solution
Step 1: Understand slice initialization in Go
To create a slice with values, use the literal syntax: []int{values}.
Step 2: Check each option
prices := []int{7, 1, 5, 3, 6} correctly creates a slice with given values. prices := [5]int{7, 1, 5, 3, 6} creates an array, not a slice. prices := make([]int, 5, 5) creates an empty slice of length 5 but no values. prices := new([]int{7, 1, 5, 3, 6}) is invalid syntax.
Final Answer:
prices := []int{7, 1, 5, 3, 6} -> Option A
Quick Check:
Slice literal = []int{values} [OK]
Hint: Use []int{...} to create slices with values directly [OK]
Common Mistakes:
Using array syntax instead of slice
Using new() incorrectly for slices
Creating empty slices without values
3. What is the output of the following Go code that finds the max profit with only one transaction?
func maxProfit(prices []int) int {
minPrice := prices[0]
maxProfit := 0
for _, price := range prices {
if price < minPrice {
minPrice = price
} else if price - minPrice > maxProfit {
maxProfit = price - minPrice
}
}
return maxProfit
}
fmt.Println(maxProfit([]int{7,1,5,3,6,4}))
medium
A. 5
B. 6
C. 4
D. 7
Solution
Step 1: Trace the loop to find minPrice and maxProfit