[Leetcode] Best Time to Buy and Sell Stock
来源:互联网 发布:验证dss算法的有效性 编辑:程序博客网 时间:2024/06/08 13:38
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.
public class Solution { public int maxProfit(int[] prices) { int len=prices.length; if(len<2) return 0; int maxprofit=0; int buy=prices[0]; for(int i=1;i<len;i++) { if(prices[i]<buy) { buy=prices[i]; } if(maxprofit<(prices[i]-buy)) maxprofit=prices[i]-buy; } return maxprofit; }}
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
- Java中反射(Reflection)的应用
- 利用C++ Boost编写扩展Python模块
- 文章标题
- Dual Palindromes(USACO)
- codeforces 682 a 解题报告 Alyona and Numbers 数论基础
- [Leetcode] Best Time to Buy and Sell Stock
- Genymotion添加模拟器时报Unable to create virtual device,Server returned HTTP status code xxx
- 部分复杂度问题
- 矩阵乘法
- TTL(time to live)生存时间
- Linux发行版的基础目录名称、命名法则及功能规定
- 子查询
- Linux的发行版以及不同发行版之间的联系和不同
- #error命令