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

## 算法描述

1. profit = 0
2. 从第2天开始遍历，判定当天价格是否大于前一天价格，若是，则将差价加到profit上，否则继续判定下一天，直到最后一天
3. 返回profit

## 代码 C

/**
* 计算最大收益
* @param prices : 每天的股票价格
* @param pricesSize : 数据规模
* @return : 最大收益
* @note : 可以买卖多次
*/
int maxProfit(int* prices, int pricesSize) {
if (pricesSize <= 1) return 0;

int max = 0, day;
for (day = 1; day < pricesSize; ++day)
if (*(prices + day) > *(prices + day - 1))
max += *(prices + day) - *(prices + day - 1);

return max;
}

## 代码 CPP

class Solution {
public:
/**
* 计算最大收益
* @param prices : 每天的股票价格
* @return : 最大收益
* @note : 可以买卖多次
*/
int maxProfit(vector<int>& prices) {
int pricesSize = prices.size();
if (pricesSize <= 1) return 0;

int max = 0, day;
for (day = 1; day < pricesSize; ++day)
if (prices[day] > prices[day - 1])
max += prices[day] - prices[day - 1];

return max;
}
};

## 运行情况

Lauguage Status Time
c Accept 4ms
cpp Accept 8ms

2015/7/8

• 本文已收录于以下专栏：

## Leetcode 122. Best Time to Buy and Sell Stock II 股票买卖2 解题报告

1 解题思想首先请看下第一个问题： Leetcode 121. Best Time to Buy and Sell Stock 股票买卖 解题报告 题目给定的数组还是一样的含义，依旧代表股票的价...

## LeetCode 122 Best Time to Buy and Sell Stock II（股票买入卖出的最佳时间 II）

• NoMasp
• 2016-03-08 19:21
• 4138

## [LeetCode]122. Best Time to Buy and Sell Stock II(最佳买卖时间 II)

122. Best Time to Buy and Sell Stock IISay you have an array for which the ith element is the price ...

## [LeetCode]121. Best Time to Buy and Sell Stock(求近期股票能获得的最大利润)

121. Best Time to Buy and Sell Stock原题链接 Say you have an array for which the ith element is the pri...

## [Leetcode]122. Best Time to Buy and Sell Stock II

122. Best Time to Buy and Sell Stock IISay you have an array for which the i-th element is the price...

## LeetCode122 Best Time to Buy and Sell Stock II

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)