当前位置:网站首页>[leetcode daily question] - 121. The best time to buy and sell stocks
[leetcode daily question] - 121. The best time to buy and sell stocks
2022-07-26 15:18:00 【IronmanJay】
List of articles
One 【 Topic category 】
- Array
Two 【 questions 】
- Simple
3、 ... and 【 Title number 】
- 121. The best time to buy and sell stocks
Four 【 Title Description 】
- Given an array prices , It's the first i Elements prices[i] Represents the number of shares in a given stock i Sky price .
- You can only choose One day Buy this stock , And choose A different day in the future Sell the stock . Design an algorithm to calculate the maximum profit you can get .
- Return the maximum profit you can make from the deal . If you can't make any profit , return 0 .
5、 ... and 【 Title Example 】
Example 1:
Input :[7,1,5,3,6,4]
Output :5
explain : In the 2 God ( Stock price = 1) Buy when , In the 5 God ( Stock price = 6) Sell when , Maximum profit = 6-1 = 5 .
Note that profit cannot be 7-1 = 6, Because the selling price needs to be higher than the buying price ; meanwhile , You can't sell stocks before you buy them .Example 2:
Input :prices = [7,6,4,3,1]
Output :0
explain : under these circumstances , No deal is done , So the biggest profit is 0.
6、 ... and 【 Topic tips 】
- 1 < = p r i c e s . l e n g t h < = 1 0 5 1 <= prices.length <= 10^5 1<=prices.length<=105
- 0 < = p r i c e s [ i ] < = 1 0 4 0 <= prices[i] <= 10^4 0<=prices[i]<=104
7、 ... and 【 Their thinking 】
- This problem can easily think of two levels f o r for for loop , But some of these examples will time out ( The time complexity is : O ( N 2 ) O(N^2) O(N2), among N N N Is array length ), The reason is that there are many unnecessary judgments , So we need to think about how to reduce these redundant judgments , You can find the maximum profit faster
- So we can easily think of greedy algorithm , We should maximize profits , That is to say, the minimum price to buy , The highest selling price , But we should pay attention to buying first , It's selling , This can be seen more clearly through examples
- Based on this idea , We maintain maxProfit Initialize to 0, That is, the minimum profit is 0,minPrice Initialize to the first value of the array , When searching backwards , If you encounter more than minPrice A small value is assigned to minPrice It means you can buy at a lower price , As for which day to sell, just search backwards , Subtraction is profit , If the profit is greater than what we maintain maxProfit, Just update maxProfit
- Return at the end of the loop maxProfit that will do
8、 ... and 【 Time frequency 】
- Time complexity : O ( N ) O(N) O(N), among N N N Is array length
- Spatial complexity : 1 1 1
Nine 【 Code implementation 】
- Java Language version
package Array;
public class p121_TheBestTimeToBuyAndSellStocks {
public static void main(String[] args) {
int[] prices = {
7, 1, 5, 3, 6, 4};
int res = maxProfit(prices);
System.out.println(res);
}
public static int maxProfit(int[] prices) {
int maxProfit = 0;
int minPrice = prices[0];
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
}
if ((prices[i] - minPrice) > maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
}
- C Language version
#include<stdio.h>
int maxProfit(int* prices, int pricesSize)
{
int maxProfit = 0;
int minPrice = prices[0];
for (int i = 0; i < pricesSize; i++)
{
if (prices[i] < minPrice)
{
minPrice = prices[i];
}
if ((prices[i] - minPrice) > maxProfit)
{
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
/* The main function is omitted */
Ten 【 Submit results 】
Java Language version

C Language version

边栏推荐
猜你喜欢

jmeter分布式

OSPF和MGRE实验

How to write the format of a university thesis?

Jintuo shares listed on the Shanghai Stock Exchange: the market value of 2.6 billion Zhang Dong family business has a strong color

How to search literature on nature?

Double the efficiency of dual screen collaboration lingyao x dual screen Pro leads the new trend of dual screen technology

CVE-2022-33891 Apache spark shell 命令注入漏洞复现

双屏协作效率翻倍 灵耀X双屏Pro引领双屏科技新潮流

装备制造业的变革时代,SCM供应链管理系统如何赋能装备制造企业转型升级

大学生如何申请实用新型专利?
随机推荐
带你熟悉云网络的“电话簿”:DNS
R language uses LM function to build multiple linear regression model, writes regression equation according to model coefficient, and uses fitted function to calculate y value (response value) vector
楚环科技深交所上市:市值27亿 民生证券是股东
NLP之NER:商品标题属性识别探索与实践
Within a week, I developed my own knowledge sharing platform
VP video structured framework
Notes (5)
[Huawei online battle service] how can new players make up frames when the client quits reconnection or enters the game halfway?
R语言使用lm函数构建多元回归模型(Multiple Linear Regression)、并根据模型系数写出回归方程、使用fitted函数计算出模型的拟合的y值(响应值)向量
What are the skills and methods of searching foreign literature
OSPF and mGRE experiments
The most detailed patent application tutorial, teaching you how to apply for a patent
VP视频结构化框架
R language ggplot2 visualization: use the ggballoonplot function of ggpubr package to visualize the balloon graph (visualize the contingency table composed of two classification variables), and config
Parallel d-pipeline: a cuckoo hashing implementation for increased throughput
蓝牙BLE4.0-HM-10设备配对指南
Qt开发高级进阶:如何在显示时适合视窗宽度和高度(fitWidth+fitHeight)
How do college students apply for utility model patents?
DevSecOps,让速度和安全兼顾
Prometheus adds redis and MySQL node monitoring