您的位置:首页 > 其它

leetcode - Best Time to Buy and Sell Stock II

2018-01-30 20:24 435 查看
Problem:

 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).

解释:买卖股票,这次运行多次交易,但要求是在买股票之前需要把股票都卖掉。

Solve: 

用贪心法求解,如果后一天价格高于前一天价格就卖出,这样能得到最大收益(单天可卖出可买进 两者不干扰)

时间复杂度O(n)AC-2mspublic int maxProfit(int[] prices) {
if(prices==null||prices.length<1){
return 0;
}
int sum=0;
for(int i=0;i<prices.length-1;i++){
if(prices[i+1]>prices[i]){//后一天价格高于前一天就卖出
sum+=prices[i+1]-prices[i];
}
}
return sum;
}后记:单天可卖出买进这个条件也挺重要的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: