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.
题意就是已经知道一支股票某些天的交易价格(看来有背景啊,连交易价格都知道了),然后限定只能交易一次,然后试着找出利益最大化的交易价格
最终题意变成了,从一个数组中找出两个元素的最大差值,动态规划,一个遍历就找到了,不过要注意的,后一个元素一定要大于前一个元素,否则就亏本了。
如:[3,2,6,5,0,3],最终的交易价格为buy=2,sell=6
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0){
return 0;
}
int buy = prices[0];
int sell = prices[0];
int profit = sell - buy;//最坏的收益是0,不能是负值,否则亏本
for(int i = 1; i < prices.length; i++){
if(prices[i] > sell){
sell = prices[i];
profit = sell - buy > profit ? sell - buy: profit;
}else if(prices[i] < buy){
buy = prices[i];
sell = prices[i];
}
}
return profit;
}
}
跟字符串相关的题比起来,这些很容易了,一看到字符串相关的那些题头就大啊!!!!
Runtime: 218 ms