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.
这道题描述的意思就是,给定一个数组prices,里面的第i个元素就是商品第i天的价格。咱们要选择某天买入,某天卖出(卖出操做确定在买入操做以后)。求可能的最大利润题目给了两个例子
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
最大利润就是进价为1,卖价为6的时候,利润为5.
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
在这个案例中,进价一直高于售价,因此没法成交,返回0。数组
public int maxProfit(int[] prices) { int maxProfit = 0; int minBuyPrice = 0; if(prices.length <= 1){ return 0; } minBuyPrice = prices[0]; for(int i=1;i<prices.length;i++){ int curPrice = prices[i]; if(curPrice < minBuyPrice){ minBuyPrice = curPrice; }else if(curPrice - minBuyPrice > maxProfit){ maxProfit = curPrice - minBuyPrice; } } return maxProfit; }