找一个数后面最大的数,求出一列数中这样的最大差值。
首先想到了两层循环O(n*n)复杂度。然后超时,代码如下:
class Solution { public: int maxProfit(vector<int> &prices) { if(prices.empty()) return NULL; if(prices.size()==1) return 0; int ans = 0; for(int i = 0;i<prices.size()-1;i++) { int max = 0; for(int j = i+1;j<prices.size();j++) { if(prices[j] - prices[i]>max) max = prices[j] - prices[i]; } if(max>ans) ans = max; } return ans; } };
然后,修改代码,使用堆,这样维护从一个元素后面的最大元素,代码如下:
class Solution { private: vector<int> heap; int heaplen; void MaxHeapfy(int root,int heaplen) { while(root<heaplen-1) { int left = 2*root + 1; int right = 2*root + 2; if(right<heaplen) { int max = heap[root]>heap[left]?root:left; max = heap[root]>heap[right]?root:right; if(max == root) break; //交换 int temp = heap[root];heap[root] = heap[max];heap[max] = temp; root = max; } else if(left<heaplen) { if(heap[left]>heap[root]) { int temp = heap[root];heap[root] = heap[left];heap[left] = temp; } break; } else break; } } void buildMaxHeap() { heaplen++; for(int i = heaplen/2;i>=0;i--) { MaxHeapfy(i,heaplen); } } public: int maxProfit(vector<int> &prices) { if(prices.empty()) return NULL; if(prices.size()==1) return 0; int ans = 0; //相反的顺序 for(int itor = 0;itor<prices.size();itor++) heap.push_back(prices[prices.size()-itor-1]); heaplen = 0; buildMaxHeap(); for(int i = prices.size()-2;i>=0;i--) { if(heap[0] - prices[i]>ans) ans = heap[0] - prices[i]; if(i == 0) break; buildMaxHeap(); } return ans; } };
还是超时。
脑残了,根本就不用堆,这个过程就一直只记录一个最大的就行,然后和当前的取差值,这样复杂度O(n).代码如下:
class Solution { public: int maxProfit(vector<int> &prices) { if(prices.empty()) return NULL; if(prices.size()==1) return 0; int ans = 0; int max = prices[prices.size()-1]; for(int i = prices.size()-2;i>=0;i--) { if(max - prices[i]>ans) ans = max - prices[i]; if(prices[i]>max) max = prices[i]; } return ans; } };