题解 | #买卖股票的最好时机#
买卖股票的最好时机
http://www.nowcoder.com/practice/64b4262d4e6d4f6181cd45446a5821ec
import java.util.*;
public class Solution {
/**
*
* @param prices int整型一维数组
* @return int整型
*/
public int maxProfit (int[] prices) {
// write code here
int length = prices.length;
//空数组处理
if(length == 0 || length == 1){
return 0;
}
int[] dp = new int[length];
int max = 0;
int min = prices[0];
int tempMax = 0;
/**
遍历数组,将新遍历得到的数(prices[i])与该数前面的的数组中最小数(min)相减,便可得到临时最大收益值(tempMax),
再将该值与当前最大收益值相比较(max),更新当前最大收益值相比较
*/
for(int i = 1;i<length;i++){
tempMax = prices[i] - min;
//更新temp值
if(tempMax > max){
max = tempMax;
}
//更新min值
if(prices[i]<min){
min = prices[i];
}
}
return max;
}
}