﻿ 【数组】Best Time to Buy and Sell Stock I/II

### Best Time to Buy and Sell Stock I

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) {
if(prices.length==0){
return 0;
}
var n=prices.length,low=2147483647,ans=0;
for(var i=0;i<n;i++){
if(prices[i]<low){
low=prices[i];
}else if(prices[i]-low>ans){
ans=prices[i]-low;
}
}

return ans;
};```

### Best Time to Buy and Sell Stock I

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

```/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
var n=prices.length,res=0;

if(n==0){
return 0;
}

for(var i=1;i<n;i++){
if(prices[i]>prices[i-1]){
res+=prices[i]-prices[i-1]
}
}

return res;
};```