赞
踩
题目描述:
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。你只能选择 某一天买入这只股票,并选择在 未来的某一个不同的日子卖出该股票。设计一个算法来计算你所能获取的最大利润。返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
// 暴力解法超时
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
int max = 0;
for(int i = 1 ; i<len ; i++){
for(int j = 0 ; j<i ; j++){
int temp = prices[i] - prices[j];
max = temp>max ? temp : max;
}
}
return max;
}
}
继续改进后…
public class Solution {
public int maxProfit(int prices[]) {
int minprice = Integer.MAX_VALUE;
int maxprofit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minprice) { // 选择最小的买入
minprice = prices[i];
} else if (prices[i] - minprice > maxprofit) { // 更新最大利润
maxprofit = prices[i] - minprice;
}
}
return maxprofit;
}
}
这里理解题意即可解决,对每一天我们需要选择最低的买入价格,然后在之后的天考虑可获利的最大价格以及继续考虑最低的买入价格,而且需要利用全局变量保存最大的利润。详细请看代码,有疑问欢迎留言。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。