既然可以无数次地购买出售,那么之后后一天比前一天贵那就卖,否则留着。所以只需要从前往后扫一次,O(n)的复杂度。
int maxProfit(vector<int> &prices) { int n = prices.size(); if(n == 0 || n == 1) return 0; int i; int previous=prices[0], latter; int result = 0; for(i = 1; i < n; i++){ latter = prices[i]; if(latter >= previous){ result = result + latter - previous; } previous = latter; } return result; }