Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Best time to Buy-Sell Stocks Program

Posted on February 1, 2022February 1, 2022 by admin

Overview

An array prices is given where prices[i] represent the price of a stock on the ith day.  You can only buy and sell once. Find the max profit you can earn by buying and selling the stock once.

Example

Input: [4,2,3,8,1]
Output: 6
Buy on the second day at 2 and sell on the 4th day at 8. Profit = 8-2 = 6

The original order should be preserved as well

Program

Here is the program for the same.

package main

import "fmt"

func maxProfit(prices []int) int {
	lenPrices := len(prices)

	buy := -1
	sell := -1

	maxProphit := 0

	for i := 0; i < lenPrices; {
		for i+1 < lenPrices && prices[i] > prices[i+1] {
			i++
		}

		if i == lenPrices-1 {
			return maxProphit
		}

		buy = i

		i++

		for i+1 < lenPrices && prices[i] < prices[i+1] {
			i++
		}

		sell = i

		if (prices[sell] - prices[buy]) > maxProphit {
			maxProphit = prices[sell] - prices[buy]
		}
		i++
	}

	return maxProphit
}

func main() {
	output := maxProfit([]int{4, 2, 3, 8, 1})
	fmt.Println(output)
}

Output

6
©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme