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)); }
}

最新文章

  1. Xilium.CefGlue CEF Chrome 自动上传文件不弹出对话框 CefDialogHandler
  2. java.lang.IllegalStateException: getWriter() has already been called for this response问题解决
  3. OC基础(27)
  4. [cc150] check palindrome of a singly linked list
  5. innobackupex 单脚本循环7天一全备6增备脚本更新
  6. jquery序列化元素
  7. C#之异步编程
  8. Object-c学习之路二(oc内存管理黄金法则1)
  9. hibernate在配置文件中配置对象关系映射文件即hbm文件路径的写法
  10. Myeclipse和windows调节成护眼色
  11. python新手---学习第一天
  12. DotNetCore跨平台~认识环境和环境变量
  13. 小tips:node起一个简单服务,打开本地项目或文件浏览
  14. Google Android SDK开发范例大全笔记 一
  15. jquery.uploadify上传插件HTML5版中文api使用说明
  16. PYTHON 实现的微信跳一跳【辅助工具】仅作学习
  17. KiCad 一款强大的 BOM 和 装配图生成插件
  18. 京东饭粒捡漏V1.1.0
  19. Scala学习(九)---文件和正则表达式
  20. SQL Server 2014备份维护计划

热门文章

  1. 深度学习面试题20:GoogLeNet(Inception V1)
  2. name_scope与variable_scope 详解
  3. Android Mboot mmc命令介绍
  4. useReducer代替Redux小案例-1(七)
  5. Page directive: invalid value for import
  6. 001 安装mysql
  7. python脚本使用源码安装不同版本的python
  8. git git push某一次的commit记录
  9. C++17 std::shared_mutex的替代方案boost::shared_mutex
  10. Microsoft VBScript 运行时错误 错误 800a005e 无效使用 Null: Replace