Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does leetcode judge the best time to buy and sell stocks

Shulou Source: shulou.com Published: 2022-06-01 13:08:51 10月01日 Update

This article mainly explains "leetcode how to judge the best time to buy and sell stocks," interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "leetcode how to judge the best time to buy and sell stocks"!

The Best Time to Buy and Sell Stocks

Given an array, its ith element is the price of a given stock on day i.

Design an algorithm to calculate the maximum profit you can make if you are allowed to complete only one trade at most (i.e., buy and sell a stock once).

Note: You cannot sell a stock before you buy it.

Example 1:

Input: [7,1,5,3,6,4]

Output: 5

Explanation: Buy on day 2 (stock price = 1) and sell on day 5 (stock price = 6), maximum profit = 6-1 = 5.

Note that the profit cannot be 7-1 = 6, because the sell price needs to be greater than the buy price; also, you cannot sell the stock before buying.

Example 2:

Input: [7,6,4,3,1]

Output: 0

Explanation: In this case, no

problem-solving ideas

1, dp[i,j] denotes the maximum difference between i, j

2, traverse i from 0 to j, position j stores the maximum value in the path, and one dimension can be omitted

3, similar position for j+1, but if j+1 is not greater than j, directly covering j+1 with j can be reduced to a constant

3, we can ask for the maximum.

Code implementation:

func maxProfit(prices []int) int { max:=0 prof:=0 for j:=0;j

Tags: Stock price profit time trading maximum timing example explanation input output exchange at the same time idea code location element content again situation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Xiaomi Shulou Tech Info Apple vpn