您的位置:首页 > 其它

LeetCode:Best Time to Buy and Sell Stock II

2015-06-24 20:31 405 查看


Best Time to Buy and Sell Stock II

 Total Accepted: 49789 Total
Submissions: 130095My Submissions

Question
 Solution 

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

Hide Tags
 Array Greedy

方法一:Greedy(贪心算法)【if(a[i]<a[i+1]){num+=a[i+1]-a[i]}】

   
public int maxProfit(int[] prices) {
int num=0;
for(int i=0;i<prices.length-1;i++){
if(prices[i]<prices[i+1]){
num+=(prices[i+1]-prices[i]);
}
}
return num;
}


方法二:动规思想

    
public int maxProfit(int[] prices) {
int i=0,num=0;
boolean buy=false;
for(;i<prices.length-1;i++){
if(buy&&prices[i]>prices[i+1]){
num+=prices[i];
buy=false;
}
if(!buy&&prices[i]<prices[i+1]){
num-=prices[i];
buy=true;
}
}
if(buy){
num+=prices[i];
}
return num;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode