I tried LeetCode every day 122. Best Time to Buy and Sell Stock II (Python, Go)

What is Leetcode

leetcode.com This is the practice of coding interviews for software developers. A total of more than 1,500 coding questions have been posted, and it seems that the same questions are often asked in actual interviews.

Introduction to golang + algorithm I will solve it with go and Python to strengthen the brain. (Python is weak but experienced)

31st question (problem 122)

  1. Best Time to Buy and Sell Stock II the issue's details

Say you have an array prices for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Japanese translation

Suppose you have an array prices whose * i * th element is the price of a particular stock on the * i * day.

Design an algorithm to find the maximum profit. You can complete as many transactions as you need (that is, buy one and sell one share multiple times).

** Note: ** You cannot make multiple transactions at the same time (that is, you must sell the stock before you can buy it again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Way of thinking

  1. Define the first maximum profit as 0
  2. Access i + 1 so array length-1 loop loop
  3. Use max, which returns the largest of the two, to determine if the next day's profit is positive
  4. If it is positive, add it to the maximum profit

Answer code

  def maxProfit(self, prices: List[int]) -> int:
        max_profit = 0
        for i in range(len(prices) - 1):
            max_profit += max(prices[i+1] - prices[i], 0)
        return max_profit

--I'll write it in Go too!

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

Recommended Posts

I tried LeetCode every day 122. Best Time to Buy and Sell Stock II (Python, Go)
I tried LeetCode every day 121 Best Time to Buy and Sell Stock (Python, Go)
I tried LeetCode every day 13. Roman to Integer (Python, Go)
I tried LeetCode every day 119. Pascal's Triangle II (Python, Go)
I tried LeetCode every day 7. Reverse Integer (Python, Go)
I tried LeetCode every day 112. Path Sum (Python, Go)
I tried LeetCode every day 20. Valid Parentheses (Python, Go)
I tried LeetCode every day 136. Single Number (Python, Go)
I tried LeetCode every day 118. Pascal's Triangle (Python, Go)
I tried LeetCode every day 125. Valid Palindrome (Python, Go)
I tried LeetCode every day 155. Min Stack (Python, Go)
I tried LeetCode every day 9. Palindrome Number (Python, Go)
I tried LeetCode every day 1. Two Sum (Python, Go)
Let Code Day 19 Starting from Zero "121. Best Time to Buy and Sell Stock"
I tried LeetCode every day 141. Linked List Cycle (Python, Go)
I tried LeetCode every day 110. Balanced Binary Tree (Python, Go)
I tried LeetCode every day 14.Longest Common Prefix (Python, Go)
I tried LeetCode every day 108. Convert Sorted Array to Binary Search Tree (Python, Go)
I tried LeetCode every day 167. Two Sum II --Input array is sorted (Python, Go)
I tried LeetCode every day 21. Merge Two Sorted Lists (Python, Go)
I tried LeetCode every day 168. Excel Sheet Column Title (Python, Go)
I tried LeetCode every day 111. Minimum Depth of Binary Tree (Python, Go)
I tried LeetCode every day 26. Remove Duplicates from Sorted Array (Python, Go)
I tried LeetCode every day 160. Intersection of Two Linked Lists (Python, Go)
[LIVE] I tried to deliver the sunrise and sunset times nationwide every day
This time I learned Python I and II at Progate.
I want to restart CentOS 8 on time every day.
I tried to illustrate the time and time in C language
I tried to display the time and today's weather w
I tried to enumerate the differences between java and python
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried to make a regular expression of "time" using Python
I tried to display the video playback time (OpenCV: Python version)
I tried to make a periodical process with Selenium and Python
I tried to easily detect facial landmarks with python and dlib
I tried to touch Python (installation)
[Introduction to Python3 Day 1] Programming and Python
I tried Grumpy (Go running Python).
How to write offline real time I tried to solve E11 with python
I tried to verify and analyze the acceleration of Python by Cython
[Markov chain] I tried to read quotes and negative emotions into Python.
I tried to create a sample to access Salesforce using Python and Bottle
How to write offline real time I tried to solve E12 with python
I tried to summarize Python exception handling
I tried to implement PLSA in Python
I tried to implement permutation in Python
Python3 standard input I tried to summarize
I tried to implement ADALINE in Python
zipline Function to buy and sell stocks
I tried to implement PPO in Python
[Python] I tried to calculate TF-IDF steadily
I tried to touch Python (basic syntax)
I tried my best to return to Lasso
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 5/22]
I tried to automate internal operations with Docker, Python and Twitter API + bonus
[ES Lab] I tried to develop a WEB application with Python and Flask ②
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 4/22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part3 / 22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 1/22]
[Python] I tried to solve 100 past questions that beginners and intermediates should solve [Part 6/22]