[数组]买股票的最佳时机[亚马逊、远景能源]

题目:假设你有一个数组,其中第i 个元素是股票在第i 天的价格。
你有一次买入和卖出的机会。(只有买入了股票以后才能卖出)。请你设计一个算法来计算可以获得的最大收益。

import java.util.*;


public class Solution {
    /**
     * 
     * @param prices int整型一维数组 
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        // write code here
        if(prices == null || prices.length == 0) return 0;
        int maxProfit = 0 ,buy = prices[0];
        for(int i=0;i<prices.length;i++){
            buy = Math.min(buy,prices[i]); //挑选出整个数组中比buy的值更小的值
            maxProfit = Math.max(maxProfit,prices[i]-buy); //挑选出数组中-buy的差值最大的值
        }
        return maxProfit;
    }
}

 

升级:股票有多次买入和卖出的机会,求最大收益

解答:不用考虑到底那一天买进,那一天卖出,只要今天的股票价格大于昨天的我就卖出,然后最后有一个总的收益值。

例如:2,5,3,8,9,7

1.赋值一个变量:total(股票的最大收益值)=0,2<5,卖出:total+=5-2=3;

2.5>3.既不买进,也不卖出。

3.3<8,卖出,total+= 3+(8-3) = 8;

4.8<9卖出,total+=8+(9-8)=9;

5.9>7.既不买进,也不卖出。所以最后的最大收益为9

import java.util.*;


public class Solution {
    /**
     * 
     * @param prices int整型一维数组 
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        // write code here
        int total = 0;
        for(int i=0;i<prices.length;i++){
            if(prices[i]<prices[i+1]){
                total += prices[i+1] - prices[i];
            }
           
        }
        return total;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值