Buying and selling stocks maximum benefit
121. Best Time to Buy and Sell Stock (Easy)
Subject description:
A stock exchange include buying and selling, only one transaction, seek the maximum benefits.
Analysis of ideas:
As long as the previous record minimum price, this price as the purchase price and the current price as the sale price, see current earnings is not the biggest gains.
Code:
class Solution {
public int maxProfit(int[] prices) {
if(prices==null||prices.length<=1)
return 0;
int min=prices[0];
int max=Integer.MIN_VALUE;
for(int i=1;i<prices.length;i++){
if(min>prices[i])
min=prices[i];
max=Math.max(max,prices[i]-min);
}
return max;
}
}