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

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

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.

思路: 维护两个变量, min 和 profit. min 的初试值为f[0], 从f[1]开始, 逐个更新profit 和 min.

时间复杂度: O(n)

空间复杂度: O(1)

public class Solution {    public int maxProfit(int[] prices) {        //只维持最小值和profit.         if (prices.length < 2) {            return 0;        }        int min = prices[0];        int profit = 0;        for (int i = 1; i < prices.length; i++) {            profit = Math.max(profit, prices[i] - min);            min = Math.min(min, prices[i]);        }        return profit;     }}

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

你可能感兴趣的文章
@RestController注解下返回到jsp视图页面
查看>>
搜索框请输入关键字 onfocus 和 onblur
查看>>
随手记:IDAPro蛮强大
查看>>
maven的下载以及安装
查看>>
数组排序
查看>>
前端性能优化-----转发的
查看>>
CentOS 7 开放防火墙端口 命令
查看>>
深入浅出Mybatis系列(八)---mapper映射文件配置之select、resultMap
查看>>
HDU 1181 变形课 【DFS】
查看>>
MySQL事务
查看>>
7月26日实习日志
查看>>
Django之 路由系统
查看>>
UVa 679 Dropping Balls (例题 6-6)
查看>>
FileWriter写数据
查看>>
【Andorid X 项目笔记】TextView字幕效果(3)
查看>>
HDU 1002
查看>>
练习markdown语法
查看>>
python 制作自定义包并安装到系统目录
查看>>
大文件排序问题
查看>>
php实现rar文件的读取和解压
查看>>