121. Best Time to Buy and Sell Stock
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1] Output: 0 In this case, no transaction is done, i.e. max profit = 0.
Solution: 对于每个点,卖出它得到的最大收益都是在它之前的最小值买入时取得的,因此遍历的时候一边求最小值,一边计算收益即可。
Code:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int min = INT_MAX;
int maxP = 0;
for(int i=0; i<prices.size(); i++){
if(min<prices[i]){
maxP = max(prices[i]-min, maxP);
}else{
min = prices[i];
}
}
return maxP;
}
};
122. Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Solution: 极小值买入,它之后的极大值卖出,对所有的极值点进行这个操作即可得到最佳收益。(我直接求了极值点,但是其实可以直接计算prices[i]-prices[i-1],然后累加所有的正值,这样求得的也是相等的结果。)
Code:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<=1) return 0;
int m = INT_MAX; //记录买下的价格, INT_MAX表示没有买
int mp = 0; //记录总利润
for(int i=0; i<prices.size()-1; i++){
if(prices[i]>m && prices[i]>=prices[i+1]){
mp += prices[i]-m;
m = INT_MAX;
}else if(prices[i]<m){
m = prices[i];
}
}
if(*(prices.end()-1)>m) mp+=*(prices.end()-1)-m;
return mp;
}
};
3. Longest Substring Without Repeating Characters
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
Solution: 对于每个字符,记录下最后一次出现的位置。对于新的字符,检查其上一次出现的位置,如果它在当前字符串内出现了,则将字符串起点重新设置为该字符的后一个位置。此外,因为前面的字符都已经检测过,确定当前字符串之内没有重复的字符,所以不需要重新遍历,只需要直接后移检测下一个新字符。
Code:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.size()==0) return 0;
int ans = 0;
int cur = 0;
int visited[256];//注意ASCII码总共有256个
fill_n(visited, 256, -1);
for(int i=0; s[i]; i++){
int length = i - visited[s[i]];
cur = min(cur+1, length);
ans = max(cur, ans);
visited[s[i]] = i;
}
return ans;
}
};