LeetCode Best Time to Buy and Sell Stock
2015-07-07 14:36
323 查看
Description:
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.
Solution:
题目的意思理解了我半天。
就是给定一个股票的数组,要求如何使得赚取的股票利润最大。也就是最大值减去最小值。
但是注意一点,股票是有时间的,从正过来的顺序,复杂度是O(n^2),但是按照时间反过来的顺序,可以降一维的复杂度,变成O(n)。
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.
Solution:
题目的意思理解了我半天。
就是给定一个股票的数组,要求如何使得赚取的股票利润最大。也就是最大值减去最小值。
但是注意一点,股票是有时间的,从正过来的顺序,复杂度是O(n^2),但是按照时间反过来的顺序,可以降一维的复杂度,变成O(n)。
import java.util.*; public class Solution { public int maxProfit(int[] prices) { if (prices.length == 0) return 0; int max = 0, maxPrice = prices[prices.length - 1]; for (int i = prices.length - 2; i >= 0; i--) { maxPrice = Math.max(maxPrice, prices[i]); max = Math.max(max, maxPrice - prices[i]); } return max; } }
相关文章推荐
- 几种排序的算法
- IE/Chrome背景图片居中1px偏移解决方法
- 【android】Android ADB 端口占用问题解决方案
- Swift语法总结补充(一)
- addChildViewController用法
- ibatis-dynamic的用法
- Netty5入门学习笔记004-使用Netty传输POJO对象(上)
- Unity3d Mathf数学运算说明
- android Toast大全(五种情形)建立属于你自己的Toast
- 图文介绍windows搭建SVN服务端的基本步骤
- hadoop一些基本知识——hadoop HDFS文件系统的特征
- 4种方法完美解决eclipse的乱码问题
- 【python】通过代理安装包
- .NET Linq 中的 Skip和Take
- PHP正则表达式
- 关于自定义View初始化时不执行onDraw方法的笔记
- ROC曲线的绘制
- Html 加载音乐代码mp3
- redis命令参考(二)
- cacti中监控squid的方法