栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode初级算法-,买卖股票数组算法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode初级算法-,买卖股票数组算法

题目:

给定一个数组 prices ,其中 prices[i] 是一支给定股票第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

JAVA:

class Solution {
    public int maxProfit(int[] prices) {
	 int length = prices.length;
		 if(length ==0) return 0;
		 int i=0;
		 int max = 0;//总收益
		 for(int j=1;jprices[j]){//当天价格比第二天贵,则不买,有票就卖掉
				 
			 }else{//买入
				 max = max + (prices[j] - prices[i]);
			 }
			 i++;
		 }
		 
		 
		return max;
    }
}

C++:

class Solution {
public:
    int maxProfit(vector& prices) {
        int length = prices.size();
         int i=0;
		 int max = 0;//总收益
		 for(int j=1;jprices[j]){//当天价格比第二天贵,则不买,有票就卖掉
				 
			 }else{//买入
				 max = max + (prices[j] - prices[i]);
			 }
			 i++;
		 }
		 
		 
		return max;
    }
};

C:

int maxProfit(int* prices, int pricesSize){
    if(pricesSize == 0) return 0;
    int i=0;
    int max = 0;//总收益
    for(int j=1;jprices[j]){//当天价格比第二天贵,则不买,有票就卖掉
				 
			 }else{//买入
				 max = max + (prices[j] - prices[i]);
			 }
			 i++;
    }

    return max;
}

ps:     没搞懂,刷算法,还有买股票,而且还提前把后面的价格标出来了,这要是能提前知道后面价格,买股票还有亏钱的吗,虽然不符合场景,但也不耽误训练数组算法。  

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/685213.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号