题目描述
假设你有一个数组,其中第i 个元素是股票在第i 天的价格。
你有一次买入和卖出的机会。(只有买入了股票以后才能卖出)。请你设计一个算法来计算可以获得的最大收益。
示例1
输入
[1,4,2]
返回值
最大收益是1块钱买,4块钱卖 4-1=3
示例2
输入
[2,4,1]
返回值
最大收益是2块钱买,4块钱卖 4-2=2
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
if(null == prices || prices.length == 0){
return 0;
}
int bestResult = 0;
int buyPrice = prices[0];
for(int i=1;i<prices.length;i++){
//最便宜的时候买 最高的时候卖 才是最划算的
//如: [8,1,2,3,4,9] 1块钱买 9块钱卖
//如: [1,2,3,4,5,9] 1块钱买 9块钱卖
//如: [8,16,1,1,1] 8块钱买 16块钱卖
//如: [9,8,7,6,5,4,3,2,1] 应该是1块钱买 1块钱卖
buyPrice = Math.min(buyPrice,prices[i]);
bestResult = Math.max(bestResult,prices[i]-buyPrice);
}
return bestResult;
}
}