题目:
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.
题目大意:
给定一个数组,里面的值表示一支股票每天的价格, 如第i天价格为prices[i],假设只能进行一次买进,一次卖出,请找出最大利润值。
解:
以prices[i]表示第i天股票价格,profit[i]表示到第i天为止所能获取的最大利润。
考虑在第n天卖出股票的最大利润 profit[n]=max(profit[n-1], prices[n]-min), 其中min为前n-1天的股票最低价。
可见我们必须在遍历数组的过程中记录最小值。
而且profit只跟前一个状态有关,所以只需用一个值来记录,而不用数组。
Java代码:
public class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) return 0; int min = prices[0]; int profit = 0; for(int i = 1; i < prices.length; i++){ min = prices[i] < min ? prices[i] : min; profit = prices[i] - min > profit ? prices[i] - min : profit; } return profit; } }
Python代码:
class Solution: # @param {integer[]} prices # @return {integer} def maxProfit(self, prices): if not prices: return 0 tmin = prices[0] profit = 0 for each in prices[1:]: profit = max(profit, each-tmin) tmin = min(each, tmin) return profit
时间: 2024-10-29 19:08:35