博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-121 Best Time to Buy and Sell Stock
阅读量:4597 次
发布时间:2019-06-09

本文共 1723 字,大约阅读时间需要 5 分钟。

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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

 

解法1:

找到每个极小值,从每个极小值之后找一个最大值,计算最大收益。比较每个最大收益。

public class Solution {    public int maxProfit(int[] prices) {        if(prices == null || prices.length == 0 || prices.length == 1)            return 0;                    int maxprofit = Integer.MIN_VALUE;        int dateIn = 0;                while(dateIn < prices.length - 1) {            //find a bottom            while(dateIn < prices.length - 1 && prices[dateIn] >= prices[dateIn+1])                dateIn++;                                    for(int i=dateIn+1; i
maxprofit) { maxprofit = prices[i] - prices[dateIn]; } } //find a top while(dateIn < prices.length - 1 && prices[dateIn] <= prices[dateIn+1]) dateIn++; } return maxprofit == Integer.MIN_VALUE ? 0 : maxprofit; }}

 

解法2:

先整理数据,计算后一个元素相对前一个元素的差值,第一个元素为0,如1,4,2整理后为0,3,-2;

计算一个连续的数组元素的和,求和的最大值。

public class Solution {    public int maxProfit(int[] prices) {        if(prices == null || prices.length < 2)            return 0;                 for(int i=prices.length - 1; i>0; i--) {            prices[i] = prices[i] - prices[i-1];        }        prices[0] = 0;                int maxprofit = 0;        int profit = 0;        for(int i=0; i
maxprofit) { maxprofit = profit; } } return maxprofit; }}

 

转载于:https://www.cnblogs.com/linxiong/p/4240086.html

你可能感兴趣的文章
Coursera公开课笔记: 斯坦福大学机器学习第十课“应用机器学习的建议(Advice for applying machine learning)”...
查看>>
竞价广告系统-广告检索
查看>>
强哥PHP面向对象学习笔记
查看>>
[转]基于.NET平台常用的框架整理
查看>>
Symbian (Read Inbox)读取收件箱的内容
查看>>
良好的编程规范
查看>>
struts2 入门
查看>>
.net 编译原理
查看>>
mean 快速开发和现有技术的对比分析
查看>>
Metro Style app :浏览器扩展
查看>>
linux的kernel是怎样工作的(TI_DM36X_ARM系统)(1)
查看>>
[luogu4310] 绝世好题 (递推)
查看>>
[luogu3203 HNOI2010] 弹飞绵羊 (分块)
查看>>
-Dmaven.multiModuleProjectDirectory system propery is not set.
查看>>
Python2 unichr() 函数
查看>>
Python 字典 copy()方法
查看>>
Minimum Path Sum
查看>>
Remove Duplicates from Sorted Array II
查看>>
常量指针和指针常量巧妙记忆方法[转]
查看>>
python-haproxy作业讲解视频总结
查看>>