您的位置:首页 > 编程语言 > C语言/C++

Leetcode 122 . Best Time to Buy and Sell Stock II

2016-10-25 11:44 330 查看
问题描述

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;
}


运行截图:

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