当前位置:网站首页>【 LeetCode 】 121. The best time to buy stocks
【 LeetCode 】 121. The best time to buy stocks
2022-07-29 15:02:00 【Crispy~】
题目
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格.你只能选择 Buy this stock one day,并选择在 Sell the stock on a different day in the future.设计一个算法来计算你所能获取的最大利润.返回你可以从这笔交易中获取的最大利润.如果你不能获取任何利润,返回 0 .
示例 1:
输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 .
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票.
示例 2:
输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0.
提示:
1 <= prices.length <= 105
0 <= prices[i] <= 104
题解
暴力遍历,Apparently time out
class Solution {
public:
int maxProfit(vector<int>& prices) {
int result=0;
int len=prices.size();
for(int i=0;i<len-1;i++)
{
for(int j=i+1;j<len;j++)
{
result = max(result,prices[j]-prices[i]);
}
}
return result;
}
};
低买高抛,So you can use a variable before loggingithe lowest value of the day,then get theiday's earnings to compare
class Solution {
public:
int maxProfit(vector<int>& prices) {
int min_price=prices[0];//记录前i天的最低价
int result=0;//存储结果
for(int k:prices)
{
result = max(result,k-min_price);//Update top yield
min_price = min(min_price,k);//更新最低价
}
return result;
}
};
边栏推荐
猜你喜欢

双非渣渣的上岸之路!备战60天,三战滴滴侥幸收获Offer

kubernetes cks strace etcd

超好用的PC端录屏软件推荐

威纶通触摸屏制作自定义欢迎界面的几种方法介绍

EA&UML日拱一卒-活动图::Feature和StuctualFeature

Domestic mobile phones turn users into their advertising broilers, no wonder consumers are buying iPhones

Nacos基础教程

xss内容总结

即刻体验 | 借助 CTS-D 进一步提升应用设备兼容性

苹果官方降价的原因找到了,它也面临销量下滑乃至出现库存问题
随机推荐
【LeetCode】350. 两个数组的交集 II
基于Flink CDC打通数据实时入湖
ArcGIS Pro与ArcGis区别
hyperbench:plugin.Open(“./fabric“): plugin was built with a different version of package golang.
为什么字符串使用final关键字
你会看 MySQL 的执行计划(EXPLAIN)吗?
兆骑科创海外高层次人才引进平台,企业项目对接,赛事活动路演
C51 存储类型与存储模式
超好用的PC端录屏软件推荐
面试官:大量请求 Redis 不存在的数据,从而影响数据库,该如何解决?
测试日报怎么写 ?
Zhaoqi Technology creates a platform for overseas high-level talent introduction, corporate project docking, and event roadshows
中国互联网科技企业群狼围攻,谷歌终于遭受重挫导致利润大跌,它为推动鸿蒙的发展而后悔...
生鲜赛道溃败中存活的本来生活,纠结生存
如何使用SparkSQL做一些简单的数据分析和可视化展示?
基于JSP&Servlet实现的众筹平台系统
arcgis中编码方式改变引起的shp文件乱码、字符截断问题处理
Work Efficiency - Fifteen minutes allows you to quickly learn Markdown syntax to proficient in typesetting practice notes
数据库mysql的执行顺序(sql语句大全实例教程)
工作效率-十五分钟让你快速学习Markdown语法到精通排版实践备忘