解题思路:由于只有一次买入和一次卖出的机会,相当于求解最大差值,可采用两层for循环遍历所有的结果。
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
int answer=0;
int cost=0;
for(int i=0;i<prices.length;i++){
for(int j=i+1;j<prices.length;j++){
cost=prices[j]-prices[i];
if(cost>answer){
answer=cost;
}
}
}
return answer;
}
}
京公网安备 11010502036488号