NC7题解 | #买卖股票的最好时机(一)#
买卖股票的最好时机(一)
http://www.nowcoder.com/practice/64b4262d4e6d4f6181cd45446a5821ec
对每天的价格: 保存一个之前的最小价格 保留一个之前的最大收益
import java.util.*;
public class Solution {
public int maxProfit (int[] prices) {
// write code here
if(prices == null || prices.length == 0){
return 0;
}
int len = prices.length;
//每天与之前最小价格的差值
int[] dp = new int[len];
//最小价格
int min = prices[0];
//最大收益
int max = 0;
for(int i = 1; i < len; i++){
dp[i] = prices[i] - min;
min = Math.min(min,prices[i]);
max = Math.max(max,dp[i]);
}
return max;
}
}