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).
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;
}
本文介绍了一种用于计算股票交易中最大可能利润的算法。该算法允许进行多次买入卖出操作,但不能同时持有多个仓位。通过Java代码实现,展示了如何在给定每日股价的情况下计算最大利润。
350

被折叠的 条评论
为什么被折叠?



