【LEETCODE】36、121题,Best Time to Buy and Sell Stock
2024-08-27 00:08:21
package y2019.Algorithm.array; /**
* @ProjectName: cutter-point
* @Package: y2019.Algorithm.array
* @ClassName: MaxProfit
* @Author: xiaof
* @Description: 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 only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock),
* design an algorithm to find the maximum profit.
* Note that you cannot sell a stock before you buy one.
*
* Input: [7,1,5,3,6,4]
* Output: 5
* Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
* Not 7-1 = 6, as selling price needs to be larger than buying price.
*
* 说白了,这个题就是求最大差额,数组是每日的价格表,我们要选2天,买进和卖出,然后获取能获益的差额,而且卖只能在买进之后
* @Date: 2019/7/2 9:42
* @Version: 1.0
*/
public class MaxProfit { public int solution(int[] prices) {
//这里有点想之前的dp一维数组的意思
//我们只需要判断当前的数据和之前最小的那个数据的差值是否是更大
int result = 0, small = 0;
if(prices.length == 0)
return 0;
else {
small = prices[0];
} for(int i = 1; i < prices.length; ++i) {
int temp = prices[i];
//我们只需要判断当前的数据和之前最小的那个数据的差值是否是更大
result = (temp - small) > result ? temp - small : result; if(temp < small) {
small = temp;
}
} return result;
} public static void main(String args[]) { int pres[] = {1,2};
System.out.println(new MaxProfit().solution(pres)); }
}
最新文章
- Xilium.CefGlue CEF Chrome 自动上传文件不弹出对话框 CefDialogHandler
- java.lang.IllegalStateException: getWriter() has already been called for this response问题解决
- OC基础(27)
- [cc150] check palindrome of a singly linked list
- innobackupex 单脚本循环7天一全备6增备脚本更新
- jquery序列化元素
- C#之异步编程
- Object-c学习之路二(oc内存管理黄金法则1)
- hibernate在配置文件中配置对象关系映射文件即hbm文件路径的写法
- Myeclipse和windows调节成护眼色
- python新手---学习第一天
- DotNetCore跨平台~认识环境和环境变量
- 小tips:node起一个简单服务,打开本地项目或文件浏览
- Google Android SDK开发范例大全笔记 一
- jquery.uploadify上传插件HTML5版中文api使用说明
- PYTHON 实现的微信跳一跳【辅助工具】仅作学习
- KiCad 一款强大的 BOM 和 装配图生成插件
- 京东饭粒捡漏V1.1.0
- Scala学习(九)---文件和正则表达式
- SQL Server 2014备份维护计划
热门文章
- 深度学习面试题20:GoogLeNet(Inception V1)
- name_scope与variable_scope 详解
- Android Mboot mmc命令介绍
- useReducer代替Redux小案例-1(七)
- Page directive: invalid value for import
- 001 安装mysql
- python脚本使用源码安装不同版本的python
- git git push某一次的commit记录
- C++17 std::shared_mutex的替代方案boost::shared_mutex
- Microsoft VBScript 运行时错误 错误 800a005e 无效使用 Null: Replace