题目描述:Say you have an array for which the i th 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.
题目意思为,假设有个数组,设为A 则A[i]代表第i天的股票价格 ,只能进行一次买卖操作,如何得到最大利润。
解题思路:这道题第一感觉就是找最大值和最小值 然后之间的差值 但是股票的性质决定了 买入点是在卖出点之前的 所以单纯的找最大值最小值 是完全不行的(如下图 绿色框应该是最低点 虽然它与最高点之间相差最大 但是高点买低点卖 不是要亏哭吗 这里求的是 最大最大最大利润!)
那应该如何解决呢?第一个想到的方法 可能就是暴力解 :假设我在第一天买入 那我分别算出在之后的几天内卖出得到,遍历所有后取最大值。
例如:假设股价分别为5 3 7 8 1 3,下表白色部分为对应的利润
分别算出在第i天买,第j天卖的最大利润(i<=j),用数组存下来,最后取最大值,代码如下:(真的很暴力,时间复杂度O(n^2))
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null)
return 0;
else if(prices.length <2)
return 0;
else{
int profit = 0;
int min = prices[0];
int max = prices[0];
for(int i=0;i<prices.length;i++){
for(int j=i+1;j<prices.length;j++){
if(prices[j]>prices[i]){
int value = prices[j]-prices[i];
if(profit<value)
profit =value;
}
}
}
return profit;
}
}
}
那有没有更好的解法呢?当然有 !!!
首先要明白一点,你的最小值 一定是在最大值前面的,所以遍历第一遍数组的时候,可以记下当下的最小值,
(这句话的意思相当于 要想你的利润最高 你的买点肯定是在卖点之前的 同一天买卖的记为0)
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null)
return 0;
else if(prices.length <2)
return 0;
else{
int min = prices[0];
int max = 0;
for(int i=0;i<prices.length;i++) {
min = Math.min(min, prices[i]);
max = Math.max(max, prices[i]-min);
}
return max;
}
}
}