# 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 不限次数买卖股票最大收益 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)