[LeetCode] Best Time to Buy and Sell Stock II

0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## [LeetCode] 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

/*****************************************************************
*  @Author   : 楚兴
*  @Date     : 2015/2/17 23:18
*  @Status   : Accepted
*  @Runtime  : 16 ms
******************************************************************/
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() <= 1)
{
return 0;
}
int max_global = 0;
int base = prices[0];
int i = 0;
while (i < prices.size() - 1)
{
if (prices[i] >= prices[i + 1])
{
max_global += prices[i] - base;
base = prices[i + 1];
}
i++;
}
max_global += prices[i] - base;

return max_global;
}
};

### 实现代码2

class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() == 0)
{
return 0;
}

int max_global = 0;
for (int i = 0; i < prices.size() - 1; i++)
{
max_global = max(max_global, max_global + prices[i + 1] - prices[i]);
}

return max_global;
}
};

+ 关注

corcosa 14985人浏览