题目
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: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
题意
告诉你,有一个数组,数组中的第i个元素代表第i天的股票的价格,现在要求你只能进行一次买卖的交易且必须先买后卖,求出所给数组中买卖交易获得的最大的利润。
题解
普通的解法:找出数组中b-a的最大值(a在前为买,b在后为卖),枚举法双层循环。
python语言
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max =-1
for buy in range(0, len(prices)):
for sell in range(buy+1, len(prices)):
if prices[sell]-prices[buy]>max:
max = prices[sell] - prices[buy]
if max<0:
return 0
else:
return max
超时。。。。。。。。。。。。肿么办?
优化,找出相对最小值,用当前的值-相对最小值与利润相比较,取最大。
python语言
#python语言
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices)==0:
return 0
min_buy = prices[0]
profit = -1
for index in range(0, len(prices)):
if min_buy > prices[index]:
min_buy = prices[index]
else:
if prices[index]-min_buy>profit:
profit = prices[index]-min_buy
return profit
C++语言
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==0)
return 0;
int min_buy=prices[0];
int profit=-1;
for(int i=0; i<prices.size(); i++)
{
if(min_buy > prices[i])
min_buy = prices[i];
else
{
if(prices[i] - min_buy > profit)
profit = prices[i] - min_buy;
}
}
return profit;
}
};