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

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

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

Example 1:

Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)


Example 2:

Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.

题目大意:

在一个数组中,用后面的元素减去前面的元素得到最大值,返回这个最大值。

思路:

可以使用双循环来出来,但是效率太低。没有通过。

采用记录当前之前的最小值,用当前值减去之前最小的值获得一个临时最大值,遍历整个数组,找到最大值。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class 
Solution {
public
:
    
int 
maxProfit(vector<
int
>& prices) {
        
if
(prices.size() <= 1)
            
return 
0;
        
int 
max = 0;
        
int 
curMin = prices[0];
         
        
for
(
int 
i = 1;i<prices.size();i++)
        
{
            
if
(prices[i] - curMin > max)
                
max = prices[i] - curMin;
            
if
(prices[i] < curMin)
                
curMin = prices[i];
        
}
        
return 
max;
    
}
};
本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1837145

转载地址:http://qhaql.baihongyu.com/

你可能感兴趣的文章
Go开发之路 -- 流程控制
查看>>
bootstrap:按钮下拉菜单
查看>>
git diff命令
查看>>
LeetCode:Climbing Stairs(DP)
查看>>
STC12C5A60S2笔记7(定时器)
查看>>
[HNOI2004]宠物收养场 BZOJ1208 splay tree
查看>>
Python标准模块--built-ins函数
查看>>
mysql超时机制
查看>>
复习java基础第一天
查看>>
程序后台服务启动,MongoDB未启动(启动较慢)/(关机重启情况下)。
查看>>
数据库系统阶段特点
查看>>
假期演练1-3
查看>>
梦断代码读后感
查看>>
js面试题
查看>>
jdbc的配置及jdbc连接常用数据库(mysql、sqlserver、Oracle)
查看>>
java获取程序执行时间
查看>>
rsync定时同步配置
查看>>
关于数据存储类型的一点分析
查看>>
Java关键字
查看>>
SharePoint 2013 工作流设计之Designer 使用“可视化视图
查看>>