leetcode day6 -- String to Integer (atoi) && Best Time to Buy and Sell Stock I II III

1、



String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical
digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

分析:此题很常见,此题的错误处理是比较简单的,如果不能转换则变为0,注意溢出问题时先使用long long来保存结果,然后做转换,而不是long,很多系统下long int和int的值范围是相同的。

代码如下:

class Solution {
public:
    int atoi(const char *str) {
        if(!str){
            return 0;
        }
        while(*str==‘ ‘){
            ++str;
        }
        bool minus = false;
        if(*str == ‘-‘){
            minus = true;
            ++str;
        }else if(*str == ‘+‘){
            ++str;
        }
        long long result = 0;
        while(*str!=‘\0‘){
            if(*str <= ‘9‘ && *str >= ‘0‘){
                result = result*10+*str-‘0‘;
                if( !minus && result>INT_MAX ){
                    return INT_MAX;
                }else if( minus && -result < INT_MIN ){
                    return INT_MIN;
                }
            }else{
                break;
            }
            ++str;
        }
        return minus==true? -(int)result:(int)result;
    }
};

2、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.

分析:求一个股票的最大收益,这个题在阿里面试过程中遇到过,不过做了变形,后来才发现leetcode中类似的题目。之前有同学去面试也出过类似的题目,求一个数组前面数字减去后面数字的绝对值的最大值,这都是一类题目,解题思路差不多。

解题思路:保存一个截止到i的股票价格的最小值和股票收益的最大值,如果prices[i]>股票价格的最小值,则有收益,比较此时收益和最大收益,更新最大收益;如果prices[i]<i前面股票价格的最小值,则更新最小值。

代码如下:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size()<2){
            return 0;
        }
        int maxProfit = 0;
        int tempProfit = 0;
        int minPrice = 0;
        for(int i=0; i<prices.size(); ++i){
            if( i==0 ){
                minPrice = prices[i];
            }
            if( prices[i] < minPrice ){
                minPrice = prices[i];
            }else{
                tempProfit = prices[i] - minPrice;
                if(tempProfit > maxProfit){
                    maxProfit = tempProfit;
                }
            }
        }
        return maxProfit;
    }
};

3、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).

分析:此题和上一题是一系列,但是可以多次买入卖出,感觉有点不知道如何求解,但仔细想,画出波浪线时,可以想到是求每个上升阶段的最大最小差值的和,想到这里就不难实现了。注意各种参数。

代码如下:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if( prices.size()<2 ){
            return 0;
        }
        int maxProfit = 0; //最大收益
        int preProfit = 0; //上一上升阶段的收益
        int curMinPrice = 0; //当前最小值
        int curMaxProfit = 0; //当前最大收益
        int buyIndex = 0; //上次购买的时间
        for(int i=0; i<prices.size();++i){
            if(i==0){
                curMinPrice = prices[i];
                buyIndex = i;
                continue;
            }
            if(prices[i] < prices[i-1]){ //在下降阶段
                if(buyIndex != i-1){ //如果是第一个下降点
                    curMinPrice = prices[i];
                    curMaxProfit = 0;
                    maxProfit += preProfit;
                    buyIndex = i;
                }else{
                    if(prices[i] < curMinPrice){ //在下降阶段
                        curMinPrice = prices[i];
                        buyIndex = i;
                    }
                }
            }else{  //一直在上升阶段
                preProfit = prices[i] - curMinPrice;
                if(preProfit > curMaxProfit){
                    curMaxProfit = preProfit;
                }
                if(i == prices.size()-1){
					maxProfit += preProfit;
				}
            }
        }
        return maxProfit;
    }
};

4、Best Time to Buy and Sell Stock III

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 at most two transactions.

Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

分析:此题和前面的类似,但是不同的是最多买两次的收益最大,首先想到的是将数组从0到数组末尾点N分别分成两半,计算分别计算左右的最大盈,利,将其加和,从这N个数中取最大的就为最多两次收益最大的值。但是这样求解局部最大盈利时子问题重复求解,想到利用空间换时间的方法,利用数组保存前一半的最大盈利,第i+1个点的盈利可以利用i个点的盈利求得;然后从后往前遍历,求i点后的最大盈利,同时将i点的最大盈利与前面数组i-1的位置元素相加(为啥是i-1位置呢,因为同一个点不能同时买入卖出),更新总最大盈利。

代码如下:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
		int length = prices.size();
		if(length<2){
			return 0;
		}
		int maxProfit = 0;

		//用数组记录从开始到每个元素位置的最大收益
		int* profit1 = new int[length];
		int buyPrice = 0;
		int tempProfit = 0;
		for(int i=0; i<length; ++i){
			if(i==0){
				profit1[i] = 0;
				buyPrice = prices[i];
				continue;
			}
			if(prices[i] > buyPrice){//如果大于前面的最小值
				tempProfit = prices[i] - buyPrice;
				if(tempProfit > profit1[i-1]){
					profit1[i] = tempProfit; //更新最大盈利
				}else{
					profit1[i] = profit1[i-1];
				}
			}else{ //如果小于前面的最小值,则更新最小值
				buyPrice = prices[i];
				profit1[i] = profit1[i-1];
			}
		}
		//从后往前遍历,计算每个元素后的最大收益
		int sellPrice = 0;
		int postMaxProfit = 0;
		int tempPrice = 0;
		for(int i=length-1; i>0; --i){
			if(i==length-1){
				sellPrice = prices[i];
				maxProfit = profit1[i];
				continue;
			}
			if(prices[i]<sellPrice){
				tempPrice = sellPrice - prices[i];
				if(tempPrice > postMaxProfit){
					postMaxProfit = tempPrice;
				}
			}else{
				sellPrice = prices[i];
			}
			if(postMaxProfit+profit1[i-1] > maxProfit){
				maxProfit = postMaxProfit+profit1[i-1];
			}
		}
		delete[] profit1;
		return maxProfit;
	}

};
时间: 2024-08-04 03:38:33

leetcode day6 -- String to Integer (atoi) && Best Time to Buy and Sell Stock I II III的相关文章

【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告

Best Time to Buy and Sell Stock I 题意:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格. 如果只允许进行一次交易,也就是说只允许买一支股票并卖掉,求最大的收益. 分析:动态规划法.从前向后遍历数组,记录当前出现过的最低价格,作为买入价格,并计算以当天价格出售的收益,作为可能的最大收益,整个遍历过程中,出现过的最大收益就是所求. 代码:时间O(n),空间O(1). Best Time to Buy and Sell Stock II 题目:用一

LeetCode之“动态规划”:Best Time to Buy and Sell Stock I &amp;&amp; II &amp;&amp; III &amp;&amp; IV

1. Best Time to Buy and Sell Stock I 题目链接 题目要求: 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), desi

[Leetcode][JAVA] Best Time to Buy and Sell Stock I, II, III

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

Best Time to Buy and Sell Stock I,II,III [leetcode]

Best Time to Buy and Sell Stock I 只能作一次操作时:维护preMin记录之前出现的最小值 代码如下: int maxProfit(vector<int> &prices) { if (prices.size() == 0) return 0; int profit = 0; int preMin = prices[0]; for (int i = 1; i < prices.size(); i++) { if (prices[i] < pr

[Leetcode] Best Time to Buy and Sell Stock I,II,III,IV

三种股票交易算法 一.交易次数没有限制 使用贪心策略,找最长递增序列,同时累加相应利润. 二.只有一次交易 使用动态规划算法,从前往后,依次记记录相应时间节点前面的最小price,同时获得在这个节点的最大利润,同时更新最小price 三.最多两次 使用两次动态规划 1.从左向右,记录在相应的时间节点卖出的最大利润,实际上就是问题二 2.从右向左,记录在相应的时间节点买入的最大利润,因此这里需要记录最大的price. 将each 的left[index]+ right[index]曲最大值. 四.

LeetCode:String to Integer (atoi)

1.题目名称 String to Integer (atoi) (字符串到数字的转换) 2.题目地址 https://leetcode.com/problems/string-to-integer-atoi/ 3.题目内容 英文:Implement atoi to convert a string to an integer. 中文:实现atoi函数,将输入的字符串(String类型)转换为整型数据(Integer类型) 提示:实现的atoi函数需要满足以下特征 忽略字符串第一个非空格字符前的所

Leetcode 数 String to Integer (atoi)

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie String to Integer (atoi) Total Accepted: 9862 Total Submissions: 67880 Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge,

LeetCode 008 String to Integer (atoi)

[题目] Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases. Notes: It is intended for this problem to b

【LeetCode】【Python题解】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). Ho