您的位置:首页 > 其它

Middle-题目23:121. Best Time to Buy and Sell Stock

2016-05-31 15:45 435 查看
题目原文:

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.

题目大意:

还是买卖股票,这回限定只能买卖一次,求最大利益。

题目分析:

本题最为简单,最低点买入最高点卖出即可,维护两个变量,一个记录最小值,一个记录当前价格减去最小值的最大值(即以今天价格卖出的profit)。

源码:(language:java)

public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0)
return 0;
int min = prices[0];
int profit = 0;
for(int price:prices) {
if(price < min)
min = price;
if(price - min > profit)
profit = price - min;
}
return profit;
}
}


成绩:

2ms,beats 60.20%,众数3ms,44.72%

cmershen的碎碎念:

一开始我误以为直接找数组的最大值和最小值相减,但是如果最小值出现在最大值后面就错了。所以维护的不是整个数组的最大值,而且当前值减去min的最大值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: