LeetCode Problem: 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:
Input:
[7,1,5,3,6,4]
Expected output:
5
If you would like to solve the problem on Leetcode, here is the link to the problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Golang Solution:
func maxProfit(prices []int) int {
minSoFar := 999999999
maxProfit := 0
for j := 0; j < len(prices); j++ {
if prices[j] - minSoFar > maxProfit {
maxProfit = prices[j] - minSoFar
}
if prices[j] < minSoFar {
minSoFar = prices[j]
}
}
return maxProfit
}