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.
这个题目就是两个嵌套循环,找到差的最大值。注意第二层循环,只要比第一层循环中的数字序号小就可以~
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
var maxP=0;
for(var i=1;i<prices.length;i++){
for(var j=0;j<i;j++){
if(prices[i]-prices[j]>maxP)maxP=prices[i]-prices[j];
}
}
return maxP;
};