Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (prices.size() < 2) {
return 0;
}
int max_sum = 0;
int sum = 0;
int more = 0;
for (int i = 1; i < prices.size(); ++i) {
more = prices[i] - prices[i-1];
if (sum + more < 0) { //当前和为负数,则从下一个重新计算
max_sum = max_sum > sum ? max_sum : sum;
sum = 0;
} else {
if (more < 0) { //出现负数时要检查当前和与最大和的大小
max_sum = max_sum > sum ? max_sum : sum;
}
sum += more;
}
}
max_sum = max_sum > sum ? max_sum : sum;
return max_sum;
}
};