Leetcode 122 . Best Time to Buy and Sell Stock II

  • 问题描述
    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天给定股票的价格。
    设计一个算法来找到最大利润。 您可以完成尽可能多的交易,你喜欢(即,买一个,多次卖股票的股票)。 但是,您不能同时参与多个交易(即,您必须在再次购买之前卖掉股票)。
    举个栗子:
    INPUT=
    7,1,5,3,6,4
    输出为7
  • 解题思路
    此题适合用贪心算法,只考虑当前的最大收益,实现局部利益最大化,故,
    定义两个变量,maxProfit储存最大收益的值,初始化为0,delta储存股票临时差值 (前后两天),
    开个循环,遍历整个股票数组,若临时差值(prices[i]-prices[i-1])为正,则加到maxProfit中(卖出股票),继续循环继续买卖,最终会取得最大的值。
  • 完整代码
#include<iostream>
#include<vector>
using namespace std;

int maxProfit(vector<int>& prices)
{
    int maxProfit = 0;
    for (int i = 1; i < prices.size(); i++)
    {
        int delta = prices[i] - prices[i-1];//求出股票的差值
        if (delta > 0)//若差值大于0,则卖出
            maxProfit += delta;
    }
    return maxProfit;
}
int main()
{
    int a[6] = { 7,1,5,3,6,4 };
    vector<int> prices(a,a+6);
    cout<<"The max profit is:\n"<<maxProfit(prices)<<endl;
    return 0;
}

运行截图:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值