- read

Leetcode using Golang #1: Earn Maximum Profit In Share trade

Udit Saurabh 12

We will try to solve one of these leet code questions in this series Leetcode using Golang. In this, we will be provided with an array of share prices which have changed in an interval of time in increasing order and we have to find the maximum profit that could be found.

The code below compares the price on a certain day with the previous day. If it has increased or if it's more it means its profit to sell on that day. Similarly, we can add all such profit earned on such days to find the maximum profit that could be earned by someone.

func main() {
res := EarnMaxProfit([]int{7, 1, 5, 3, 6, 4, 20})
fmt.Println(res)
}
func EarnMaxProfit(share_price []int) int {
max_profit := 0
for i := 1; i < len(share_price); i++ {
if share_price[i-1] < share_price[i] {
max_profit = max_profit + (share_price[i] - share_price[i-1])
}
}
return max_profit
}

Result