problem Ⅰ
1014. Best Sightseeing Pair
You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.
The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them.
Return the maximum score of a pair of sightseeing spots.
Example 1:
Input: values = [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
Example 2:
Input: values = [1,2]
Output: 2
solution 1
class Solution {
public:
int maxScoreSightseeingPair(vector<int>& values) {
int cur = values[0]-1, maxs = INT_MIN;
for(int i=1; i<values.size(); i++){
maxs = max(maxs, cur + values[i]);
cur = max(cur, values[i])-1;
}
return maxs;
}
};
problem Ⅱ
121. Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
wrong solution
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==1)return 0;
int mins = prices[0], maxs = prices[1];
int pmin = 0, pmax = 1;
for(; pmax < prices.size(); pmax++){
if(prices[pmax] >= maxs){
maxs = prices[pmax];
for(; pmin < pmax; pmin++){
if(prices[pmin] < mins)
mins = prices[pmin];
}
}
}
if(maxs - mins > 0) return maxs - mins;
else return 0;
}
};
correct solution
class Solution {
public:
int maxProfit(vector<int>& prices) {
int left = 0, right = 1, maxs = 0;
for(; right < prices.size(); right++){
if(prices[right] > prices[left]){
maxs = max(maxs, prices[right]-prices[left]);
}else left = right;
}
return maxs;
}
};