Skip to content

Instantly share code, notes, and snippets.

@krarjun90
Last active July 27, 2023 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krarjun90/ddadce4ac08b2db8554938a2a2b2d1a3 to your computer and use it in GitHub Desktop.
Save krarjun90/ddadce4ac08b2db8554938a2a2b2d1a3 to your computer and use it in GitHub Desktop.
cassidoo#310
package main
import (
"fmt"
"sort"
)
func main() {
fmt.Printf("Hello Cassidoo!\n")
input := []int{7, 1, 5, 3, 6, 4}
fmt.Printf("\nMax Profit %v", maximumProfit(input))
}
func maximumProfit(input []int) int {
mapStockValuesToDayIndex := make(map[int][]int)
var sortedUniqueStockValues []int
var buyDay, sellDay, maxProfit int
for index := range input {
currentElement := input[index]
mapStockValuesToDayIndex[currentElement] = append(mapStockValuesToDayIndex[currentElement], index)
}
for key := range mapStockValuesToDayIndex {
sortedUniqueStockValues = append(sortedUniqueStockValues, key)
}
sort.Sort(sort.Reverse(sort.IntSlice(sortedUniqueStockValues)))
for dayIndex, dayStockVal := range input {
fmt.Printf("\nIf you buy on day %v at %v ", dayIndex+1, dayStockVal)
sellValue := 0
for _, stockValue := range sortedUniqueStockValues {
if stockValue > dayStockVal {
for _, index := range mapStockValuesToDayIndex[stockValue] {
if index > dayIndex {
sellValue = stockValue
fmt.Printf("sell on day %v at value %v ", index+1, sellValue)
profit := sellValue - dayStockVal
fmt.Printf("then profit is %v", profit)
if profit > maxProfit {
buyDay = dayIndex
sellDay = index
maxProfit = profit
}
break
}
}
if sellValue > 0 {
break
}
}
}
if sellValue == 0 {
fmt.Printf("then you can not sell at profit")
}
}
fmt.Printf("\nBuy on day %v and sell on day %v to get max profit %v", buyDay+1, sellDay+1, maxProfit)
return maxProfit
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment