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.
Accept: 5ms
思路:
- 先两两相减得到前后2天的差值:diff[i] = prices[i+1] - prices[i];
- 问题就简化为在diff数组中找到和最大的连续子串问题:当前为i,总和为sum,下一个为i+1,则:
- 如果 diff[i+1] >=0,则sum += diff[i+1];
- 如果 diff[i+1] < 0,则:
- 如果 sum + diff[i+1] > 0,则选择i+1,
- 否则:在i+1这里断开。
int diff[100000];
int maxProfit(int prices[], int n){
for (int i = 0; i < n - 1; ++i) {
diff[i] = prices[i+1] - prices[i];
}
int i = 0;
for (; i < n - 1 && diff[i] <= 0; ++i) /* nothing */;
int max = 0;
int sum = 0;
for (; i < n - 1; ++i) {
int next = diff[i] + sum;
if (next <= 0) {
sum = 0;
continue;
}
sum += diff[i];
if (sum > max) {
max = sum;
}
} // for
return max;
}