121. Best Time to Buy and Sell Stock
来源:互联网 发布:淘宝全屏海报怎么设置 编辑:程序博客网 时间:2024/05/20 17:41
Say you have an array forwhich the ith element is the price of a given stock on day i.
If you were only permitted tocomplete 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: 5
max. difference = 6-1 = 5 (not7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transactionis done, i.e. max profit = 0.
翻译:有一整形数组,数组的a[i]代表第i天股票的价格,只能买卖一次,求获利最大值。这题不难,只用求出最小值和最大值的差就行了。但是股票在卖之前必须要买。具体代码如下:
public class Solution {
public int maxProfit(int[] prices) {
int result=0;
if(prices.length==0) {
return 0;
}
int min=prices[0];
for(int i=0;i<prices.length;i++){
if(prices[i]>=min){
if(prices[i]-min>result){
result=prices[i]-min;
}
}else{
min=prices[i];
}
}
return result;
}
}
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- 常见的各种命令
- stanford sentiment treebank 数据集
- 剑指Offer-9.斐波那契数列
- 神经网络之梯度下降与反向传播(上)
- 《Android Studio日志工具Log之最强辅助》
- 121. Best Time to Buy and Sell Stock
- maven项目中pom.xml一些属性记录
- 【C++】学习笔记三十七——递归
- HTML5 笔记1— details元素、mark元素、progress元素、meter元素
- <感悟4>
- 如何查看某个端口被谁占用
- 神经网络之梯度下降与反向传播(下)
- MQTT---HiveMQ源码详解(十)Netty-Statistics
- list用法