题目内容:
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).
翻译:
给出一个数组,该数组表示某只股票每天的价格
设计一个求最大收益的算法,你可以进行多次交易,但是每次只能买一支或卖一支,且手上一次最多只有一支股票。
方法一
思路:对数组进行循环,将每天的数据与后一天的对比,若后一天的收益比前一天大,则总收益=总收益+后一天收益-前一天收益
代码(java版)
public class Solution {
public static int maxProfit(int[] prices) {
int nlen = prices.length;
if(nlen<2) return 0;
int maxProfit = 0;
for(int i = 1; i<nlen; i++){
if(prices[i]>prices[i-1]){
maxProfit = maxProfit + (prices[i]-prices[i-1]);
}
}
return maxProfit;
}
}
方法二(摘自:http://m.blog.youkuaiyun.com/blog/mason_mow/27207175)
思路:对于一个股票的价格走势,多次买入卖出使收益最大。目标就是找出这个股市波动曲线中一段段的上升曲线,对于每一个上升曲线,计算其收益,最后受益相加。
代码:
public static int maxProfit(int[] prices) {
if (prices.length == 0)
return 0;
int i = 0;
int profit = 0;
int begMin = prices[0];
for (i = 1; i < prices.length; ++i) {
if (prices[i] < prices[i - 1]) {
profit += prices[i - 1] - begMin;
begMin = prices[i];
}else if (i == prices.length-1){
profit += prices[i] - begMin;
}
begMin = Math.min(begMin, prices[i]);//经验证,此句可省略
}
return profit;
}
本文介绍了一种计算股票买卖最大利润的算法。通过两次遍历价格数组的方式,找到所有上升趋势段并累加利润,实现了在限制条件下获取最大收益的目标。
350

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



