LeetCode------Best Time to Buy and Sell Stock II
2014-12-06 15:06
344 查看
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).
public static int maxProfit(int[] prices){
int profit=0,flag=0,present=0;
for(int i=0;i<prices.length;i++){
if((i!=(prices.length-1)) && flag==0 && prices[i+1]>prices[i] ){
present = prices[i];
flag=1;
}
if(flag==1 && i!=(prices.length-1) && prices[i+1]<prices[i]){
profit += prices[i] - present;
flag = 0;
}
if(flag==1 && i==(prices.length-1)){
flag = 0;
profit += prices[i]-present;
}
}
return profit;
}
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).
最烦LeetCode没有样例输入和输出了,看了好一会才看懂题目什么意思!
Java代码:public static int maxProfit(int[] prices){
int profit=0,flag=0,present=0;
for(int i=0;i<prices.length;i++){
if((i!=(prices.length-1)) && flag==0 && prices[i+1]>prices[i] ){
present = prices[i];
flag=1;
}
if(flag==1 && i!=(prices.length-1) && prices[i+1]<prices[i]){
profit += prices[i] - present;
flag = 0;
}
if(flag==1 && i==(prices.length-1)){
flag = 0;
profit += prices[i]-present;
}
}
return profit;
}
相关文章推荐
- LeetCode_Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- 【leetcode】Best Time to Buy and Sell Stock II
- [leetcode刷题系列]Best Time to Buy and Sell Stock II
- [leetcode]Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II Solution
- leetcode 61: Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- [Leetcode 51] 122 Best Time to Buy and Sell Stock II
- leetcode--Best Time to Buy and Sell Stock II
- [LeetCode]Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock I II III
- [Leetcode] Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode: Best Time to Buy and Sell Stock II
- [LeetCode 122] - 买入与卖出股票的最佳时机II(Best Time to Buy and Sell Stock II)