题目描述
假设你有一个数组,其中第\ i i 个元素是股票在第\ i i 天的价格。
你有一次买入和卖出的机会。(只有买入了股票以后才能卖出)。请你设计一个算法来计算可以获得的最大收益。
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
if(prices==null||prices.length<=1)return 0;
int min=prices[0],maxProfit=0;
for(int i=1;i<prices.length;i++){
//查找最小值
min=Math.min(min,prices[i])==min?min:prices[i];
//从左往右寻找最大收益
maxProfit=Math.max(maxProfit,prices[i]-min);
}
return maxProfit>0?maxProfit:0;
}
}