暴力法
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int yin = 0;
//int flag = 0;
for(int i = 0; i < n-1; i++)
{
for(int j = i+1; j < n; j++)
{
//yin = Math.max(prices[j] - prices[i], yin);
int cha = prices[j] - prices[i];
if(cha > yin)
yin = cha;
}
}
return yin;
}
}
一次遍历:保存每次股票最低的点,往后计算与当前最低值的差值,保存差值最大的点
class Solution {
public int maxProfit(int[] prices) {
int minprice = Integer.MAX_VALUE;
int cha = 0;
for(int i = 0; i < prices.length; i++ )
{
if(prices[i] < minprice)
{
minprice = prices[i];
}
else
{
cha = Math.max(prices[i] - minprice, cha);
}
}
return cha;
}
}