Best Time to Buy and Sell Stock II

Solution in Go

A simple solution is to add all the price increases.

func maxProfit(prices []int) int {
    profit := 0
    
    for i := 0; i < len(prices) - 1; i++ {
        if prices[i] < prices[i+1] {
            profit += prices[i+1] - prices[i]
        }
    }
    
    return profit
}

A bit more involved solution is by keeping track of stock in hand, buy if there is a price increase and sell if there is price drop.

func maxProfit(prices []int) int {
    profit := 0
    currentPrice := -1 // -1 denotes we don't hold any stock yet
    
    for i := 1; i < len(prices); i++ {
        if currentPrice == -1 {
            if prices[i - 1] < prices[i] {
                currentPrice = prices[i - 1]
            }
        } else {
            if prices[i - 1] > prices[i] {
                profit += prices[i - 1] - currentPrice
                currentPrice = -1
            }
        }
    }
    
    // sell in case we are holding anything
    if currentPrice != -1 {
        profit += prices[len(prices) - 1] - currentPrice
    }
    
    return profit
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.