您的位置:首页 > 其它

[LeetCode][Jave] Best Time to Buy and Sell Stock II

2015-05-19 20:50 309 查看

题目:

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

题意:

给定一个数组,数组中的第i个元素值为给定的一只股票在第i天的价格。

设计一个算法找到这只股票的最大收益。你可以任意次数的买卖这支股票。但是,在你买入这支股票之前,你必须先卖掉。

算法分析:

这个题特别容易想复杂,其实就是只要找到递增的区间差就行(注意:不可以在一天当中同时出现买和卖的行为)

代码:

public class Solution
{
public  int maxProfit(int[] prices)
{
int prf=0;
if(prices==null||prices.length<=1)
return 0;
for(int i=1;i<prices.length;i++)
{
if(prices[i-1]<=prices[i])
{
prf+=prices[i]-prices[i-1];
}
}
return prf;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: