问题一 Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.public int maxProfit(int[] prices) {
assert prices.length >= 0;
int min = Integer.MAX_VALUE;
int max = 0;// 寻找最小的,一次保存最大的
for (int p : prices) {
min = Math.min(min, p);
max = Math.max(max, p - min);
}
return max;
}public int maxProfit(int[] prices) {
assert prices.length >= 0;
int local = 0;
int max = 0;
for (int i = 1; i < prices.length; i++) {
local = prices[i] - prices[i - 1];
int x = local > 0 ? local : 0;
max += x;
}
return max;
}public int maxProfit(int[] prices) {
if (prices.length < 2)
return 0;
int[] left = new int[prices.length];// 记录了prices[0..i]的最大profit
int[] right = new int[prices.length];// 记录了prices[i..n]的最大profit
int left_min = prices[0];
for (int i = 1; i < prices.length; i++) {
left_min = Math.min(left_min, prices[i]);
left[i] = Math.max(prices[i] - left_min, left[i - 1]);
}
int right_max = prices[prices.length - 1];
for (int i = prices.length - 2; i >= 0; i--) {
right_max = Math.max(right_max, prices[i]);
right[i] = Math.max(right_max - prices[i], right[i + 1]);
}
int max = 0;
for (int i = 1; i < prices.length; i++) {
max = Math.max(max, left[i] + right[i]);
}
return max;
}这时可以定义一个2位数组,用来保存买入和卖出的index,当全局的收益有变化时,更新即可。
public int[] maxProfits(int[] prices) {
assert prices.length >= 0;
int min = Integer.MAX_VALUE;
int[] res = new int[2];// 最终保存的最大
int[] temp = new int[2];// index的临时的记录
int max = 0;
for (int i = 0; i < prices.length; i++) {
if (min > prices[i]) {
min = prices[i];
temp[0] = i;
}
if (max < prices[i] - min) {
temp[1] = i;
max = prices[i] - min;
res = Arrays.copyOf(temp, 2);
}
}
System.out.println(res[0] + "----" + res[1]);
return res;
}Best Time to Buy and Sell Stock
原文地址:http://blog.csdn.net/lgcssx/article/details/41629439