题目描述
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
示例输入输出:
[7, 1, 5, 3, 6, 4]===>[5]//因为6-1=5
[7, 6, 4, 3, 1]===>[0]//因为一直在亏损,没有进行购入交易
大白话
给出一组代表股票每日价值的数组,用户可选择任意时刻购入抛出,现在要用户在最佳的时间购入抛出股票以获得最大的收益,求最大收益
原题目链接
121. Best Time to Buy and Sell Stock
思路
首先理清下题目的意思,就是求数组序列中的最大差值,只不过只能是后一个元素比前一个大的情况,不能是前一个比后一个大的情况下的差值
于是我的想法又出来了。what a 首当其冲的 algorithms
var maxProfit = function(prices) {
var max_profit = 0;
var cur_profit = 0;
for(var i = 0;i<prices.length;i++){
for(var j = i+1;j<prices.length;j++){
//两次循环,比较当前元素和它以后的所有的元素
if(prices[j]>prices[i]){//如果比当前的大
cur_profit = prices[j] - prices[i];
//那么当前的利润就是它了!
}
if(cur_profit>max_profit){
max_profit = cur_profit;
//然后在当前利润的所有值中换最大利润
}
}
}
return max_profit;
};
AC代码
var maxProfit = function(prices) {
var max_profit = 0;
var cur_profit = 0;
for(var i = 0;i<prices.length;i++){
for(var j = i+1;j<prices.length;j++){
if(prices[j]>prices[i]){
cur_profit = prices[j] - prices[i];
//console.log(cur_profit);
}
if(cur_profit>max_profit){
max_profit = cur_profit;
}
}
}
return max_profit;
};
// 更高效的
var min = Number.MAX_SAFE_INTEGER; //js整数里的最大值
var max = 0;
for (var i = 0; i < prices.length; i++) {
min = Math.min(min, prices[i]);
console.log(min);
max = Math.max(max, prices[i] - min);
console.log(max);
}
return max;