题目:
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例:
代码:
- 解法一
//暴力破解 两层for循环
class Solution {
public int maxProfit(int[] prices) {
if(prices==null||prices.length==0)
return 0;
int max=0;
for(int i=prices.length-1;i>0;i--){
for(int j=i-1;j>=0;j--){
if((prices[i]-prices[j])>max)
max=prices[i]-prices[j];
}
}
return max;
}
}
- 解法二
class Solution {
public int maxProfit(int[] prices) {
int minprice = Integer.MAX_VALUE; //定义买入 为最大值
int maxprofit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minprice)
minprice = prices[i]; //更新买入价格
else if (prices[i] - minprice > maxprofit) //更新最大利润
maxprofit = prices[i] - minprice;
}
return maxprofit;
}
}
- 解法三
//和解法一思路类似
class Solution {
public int maxProfit(int[] prices) {
int t = 0; //返回的最终差价
for(int i = 0; i < prices.length; ++i){
int max = 0;
int temp = 0; //中间差价
if(i != prices.length-1 && prices[i] < prices[i+1]){ //得到每个最低点 并防出界
max = prices[i];
for(int j = i; j < prices.length; ++j) //得到该低点对应的最高点
if(max < prices[j])
max = prices[j];
}
temp = max - prices[i];
if(t < temp) // 得到最高差价
t = temp;
}
return t;
}
}
- 解法四
class Solution {
public int maxProfit(int[] prices) {
if(prices.length<=1){
return 0;
}
int buy=-prices[0],sell=0;
for (int i = 1; i <prices.length ; i++) {
buy=Math.max(buy,-prices[i]);
sell=Math.max(sell,prices[i]+buy);
}
return sell;
}
}