121 Best Time to Buy and Sell Stock 买卖股票的最佳时机
假设你有一个数组,其中第 i 个元素是一支给定股票第 i 天的价格。
如果您只能完成最多一笔交易(即买入和卖出一股股票),则设计一个算法来找到最大的利润。
示例 1:
输入: [7, 1, 5, 3, 6, 4]
输出: 5
最大利润 = 6-1 = 5(不是 7-1 = 6, 因为卖出价格需要大于买入价格)
示例 2:
输入: [7, 6, 4, 3, 1]
输出: 0
在这种情况下, 没有交易完成, 即最大利润为 0。
详见:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
Java实现:
class Solution {public int maxProfit(int[] prices) {int n=prices.length;if(n==0||prices==null){return 0;}int mn=prices[0];int profit=0;for(int i=1;i<n;++i){if(prices[i]<mn){mn=prices[i];}if(prices[i]-mn>profit){profit=prices[i]-mn;}}return profit;}
}
参考:https://www.cnblogs.com/grandyang/p/4280131.html
转载于:https://www.cnblogs.com/xidian2014/p/8722098.html
121 Best Time to Buy and Sell Stock 买卖股票的最佳时机相关推荐
- 121. Best Time to Buy and Sell Stock买卖股票的最佳时机
You are given an array prices where prices[i] is the price of a given stock on the ith day. 给定一个数组 p ...
- Leetcode NO.121 Best Time To Buy And Sell Stock 买卖股票时间
文章目录 1.问题描述 2.测试用例 示例 1 示例 2 3.提示 4.代码 1.暴力 code 复杂度 2.动态规划 code 复杂度 1.问题描述 给定一个数组 prices ,它的第 i 个元素 ...
- [LeetCode] Best Time to Buy and Sell Stock 买卖股票的最佳时间
Say you have an array for which the ith element is the price of a given stock on day i. If you were ...
- LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
翻译 话说你有一个数组,其中第i个元素表示在第i天的股票价格.如果你被只被允许最多一次交易(例如,买入然后卖出一个股票),设计一个算法并找出最大利润. 原文 Say you have an array ...
- 【贪心 和 DP + 卖股票】LeetCode 121. Best Time to Buy and Sell Stock
LeetCode 121. Best Time to Buy and Sell Stock Solution1:我的答案 动态规划和贪心不要区分的那么明显嘛~~~ class Solution { p ...
- [LeetCode]Buy and Sell Stocks 买卖股票问题
LeetCode上关于买卖股票的问题一共有五道,题号分别为121,122,123,188,309. 此类问题的基本描述即给出一个序列prices[],prices[i]代表第i天股票的价格. 如果当天 ...
- LeetCode 121. Best Time to Buy and Sell Stock
题目: Say you have an array for which the ith element is the price of a given stock on day i. If you w ...
- 121 Best Time to Buy and Sell Stock
输入:一个数组prices,prices[i]表示第i天股票的价格. 输出:买卖股票的最大收益. 规则:只允许最多买一次,最多卖一次股票.如果觉得价格不合适,可以不买卖. 分析1:最先想到的是暴力搜索 ...
- LeetCode 121 Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i. If you were ...
最新文章
- Java项目:兼职平台系统(java+Springboot+ssm+HTML+maven+Ajax+mysql)
- 安全多方计算(MPC)从入门到精通:JUGO-IDE及SDK
- win 开机 Microsoft corparation 滚动栏
- RPA学习-关于读 csv 文件报错问题
- Ubuntu12.04 安装vim出错
- linux shell编程之菜单选择(二)
- django实现图片上传和显示
- dll 重新加密打包的问题
- 54部经典国外动画片---送给70-80年代的朋友
- Ambari技术介绍-尚硅谷大数据培训
- 批处理打开URL总结
- android dff播放器,无损音乐文件的整理(dff、dsf篇)
- 牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。
- 清华梦的粉碎—写给清华大学的退学申请
- JS代码转换d.ts语法
- DISPLAY尚未设置
- 喜大普奔!rgee能用了!R语言也可以使用Google Earth Engine了!
- 计算机系统操作高级工考试题,计算机系统操作高级工试题和答案.doc
- Rebranding (字典序替换 思维)
- 对抗样本生成算法复现代码解析:FGSM和DeepFool