LeetCode:股票购买出售的最大利润

Say you have an array for which the (i)th element is the price of
a given stock on day i.Design an algorithm find the maximum profit.
You may complete as many transactions as you like(i.e.,buy one and
sell one share of the stock multiple times).

Note:You may not engage in multiple transactions at the same time(
i.e.,you must sell the stock before you buy again).

Example 1:
Input:[7,1,5,3,6]
Output:7

Explanation:Buy on day 2(price=1) and sell on day 3(price=5),profit=
5-1=4.The buy on day 4(price=3) and sell on day 5(price=6).profit=
6-3=3;

Example 2:
Input:[1,2,3,4,5]
Output:4

Explanation:Buy on day 1(price=1) and sell on day 5(price=5),profit=
5-1=4.Note that you cannot buy on day 1,buy on day 2 and sell them
later,as you are engaging multiple transaction at the same time.You
 must sell before buying again.

题目大意:
给定一个数组,它的第i个元素是一支给定股票第i天的价格.设计一个算法来计算你所能获取的最大
利润.你可以尽可能地完成更多的交易(多次买卖一支股票).注意:你不能同时参与多笔交易(你必须
在每次购买前出售掉之前的股票).

方法1:
最大收益必然是每次跌入时就买入,涨到顶峰的时候就抛出.只要有涨峰就开始计算赚的钱,连续涨可以用
两两相减进行累加来计算,两两相减2累加,相当于涨到波峰的最大值减去波谷的值.

方法2:
把数组中的数字以折线图的形式反映,我们发现这就是有波峰和波谷的折线图.而我们要找最大利润,
其实就是我们要找到所有挨得最近的一组波谷和波峰差值的总和;
在这种情况下:只需要一次循环,不停的找某个波谷的值,然后紧接着找到离它最近的一个波峰的值,
他们的差值就是最大利润的一部分;然后接下去再找下一组波谷和波峰;
*/
package main

import "fmt"

func maxProfit(prices []int)int{
	profit:=0
	for i:=1;i<len(prices);i++{
		if prices[i]-prices[i-1]>0{
			profit+=prices[i]-prices[i-1]
		}
	}
	return profit
}
func main(){
	fmt.Println("股票的最大利润")
	prices:=[]int{7,1,5,3,6}
	fmt.Println(maxProfit(prices))
}
#include <iostream>
#include <vector>

using namespace std;

class Solutin{
public:
    int maxProfit(vector<int>& prices){
        int peak,valley,maxprofit=0,i=1,n=prices.size();
        while(i<n){
            while(i<prices.size()&&prices[i]-prices[i-1]<=0)
               i++;/*波谷*/
            valley=prices[i-1];
            while(i<prices.size()&&prices[i]-prices[i-1]>=0)
               i++;/*波峰*/
            peak=prices[i-1];
            maxprofit+=peak-valley;
        }
        return maxprofit;
    }
};
int main(int argc,char* argv[]){
    vector<int> prices{7,1,5,3,6,4};
    cout<<Solutin().maxProfit(prices)<<endl;
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路上的追梦人

您的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值