Leetcode Best Time to Buy and Sell Stock
来源:互联网 发布:高通编译linux 编辑:程序博客网 时间:2024/05/22 08:32
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.
Difficulty: Easy
public class Solution { public int maxProfit(int[] prices) { if(prices.length == 0 || prices.length == 1) return 0; int min = prices[0], ans = 0; for(int i = 1; i < prices.length; i++){ if(prices[i] <= min){ min = prices[i]; continue; } ans = Math.max(ans, prices[i] - min); } return ans; }}
0 0
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- Codeforces Round #361 (Div. 2) D RMQ+二分
- 查看网页中的密码
- java之原子性
- Java反射
- [Leetcode]100. Same Tree
- Leetcode Best Time to Buy and Sell Stock
- 静态代理模式总结
- struts2--使用域模型完成注册的简单实例
- maven初识
- PAT L2-004. 这是二叉搜索树吗?
- codeforces Round #361 D. Friends and Subsequences (ST表,二分)
- Hashtable与HashMap的区别
- Leetcode Best Time to Buy and Sell Stock II
- 在数组 arr 中,查找值与 item 相等的元素出现的所有位置