【LeetCode】121.best-time-to-buy-and-sell-stock
来源:互联网 发布:淘宝自动回复短语 创意 编辑:程序博客网 时间:2024/06/01 08:54
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.
方法一:O(n^2)
1、遍历所有i,对每个i遍历j from i+1 to n,找到最大的差。但没有体现动态规划的思想。
2、遍历所有i,对每个i找前i-1个中最小的元素,若arr[i]-min>profit[i-1],则更新profit[i],否则,profit[i]=profit[i-1]。体现了动态规划思想,但复杂度还是很高。
方法二:O(n)
仔细分析问题可以发现,核心就是找波谷min,然后计算其之后的最大差(找波峰max)。
public class Solution { public int maxProfit(int prices[]) { int minprice = Integer.MAX_VALUE; int maxprofit = 0; for (int i = 0; i < prices.length; i++) { if (prices[i] < minprice) minprice = prices[i]; else if (prices[i] - minprice > maxprofit) maxprofit = prices[i] - minprice; } return maxprofit; }}
阅读全文
0 0
- LeetCode 121. Best Time to Buy and Sell Stock
- [Leetcode] 121. Best Time to Buy and Sell Stock
- [leetcode] 121. Best Time to Buy and Sell Stock
- 【leetcode】121. Best Time to Buy and Sell Stock
- [leetcode] 121. Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock LeetCode
- [LeetCode]121. Best Time to Buy and Sell Stock
- Leetcode 121. Best Time to Buy and Sell Stock
- leetcode 121. Best Time to Buy and Sell Stock
- LeetCode 121. Best Time to Buy and Sell Stock
- LeetCode题解:121. Best Time to Buy and Sell Stock
- LeetCode *** 121. Best Time to Buy and Sell Stock
- 【leetcode】121. Best Time to Buy and Sell Stock
- #leetcode#121. Best Time to Buy and Sell Stock
- LeetCode 121. Best Time to Buy and Sell Stock
- 121.[Leetcode]Best Time to Buy and Sell Stock
- leetcode 121. Best Time to Buy and Sell Stock
- Leetcode 121. Best Time to Buy and Sell Stock
- 2017 ccpc秦皇岛M Safest Buildings
- 用户配置文件和密码配置文件、用户组及用户管理
- php 输出语句
- BZOJ3673 & BZOJ3674 可持续化并查集 【可持续化线段树维护可持续化数组】
- 笔记: http_proxy有关的环境变量
- 【LeetCode】121.best-time-to-buy-and-sell-stock
- FZU
- AVL树的python实现
- 【iOS】Cocoa(iOS,OSX)安保系统设计实现
- Java基础知识02-流程控制-do while
- 计算机网络复习笔记---第一章(计算机网络和因特网)
- 企业资深架构师,月薪几十万的技术大牛,总结的七条经验
- 串插入
- linux 进程调度切换过程分析