题解 | #买卖股票的最好时机(一)#
买卖股票的最好时机(一)
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 min = Integer.MAX_VALUE;
int result = 0;
for (int p : prices) {
if(min > p) {
min = p;
}
int t = p - min;
if (t > result) {
result = t;
}
}
return result;
}
}