Problem
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.
Code
int maxProfit(vector<int> &prices) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int n = prices.size(); if(n < 2) return 0; for(int i = 0;i < n - 1;++i){ prices[i] = (prices[i + 1] - prices[i]); } vector<int> M(n - 1); int max_sum = M[0] = prices[0]; for(int i = 1;i < n - 1;++i){ M[i] = prices[i]; if(M[i - 1] > 0) M[i] += M[i - 1]; if(max_sum < M[i]) max_sum = M[i]; } return (max_sum > 0 ? max_sum : 0); }
No comments:
Post a Comment