Skip to content

Latest commit

 

History

History
58 lines (46 loc) · 1.58 KB

11_贪心.md

File metadata and controls

58 lines (46 loc) · 1.58 KB

贪心

1、连续子数组的最大和(45)

连续子数组的最大和

//思路:
//贪心策略:遍历数组,到当前位置,上次保留的最大值如果为负数就要刷新一次,
// 即 curSum<=0时,当即果断丢弃,因为只会越加越小,刷新为当前值;
// 如果为正数,继续累加。

public int FindGreatestSumOfSubArray(int[] array) {
    if (array == null || array.length == 0){
        return 0;
    }
    int curSum = 0;
    int res= Integer.MIN_VALUE;
    for(int i=0;i<array.length;i++){
        if(curSum<=0){
            curSum = array[i];
        }else{
            curSum += array[i];
        }
        res = Math.max(res,curSum);
    }
    return res;
}

2、买卖股票的时机

Leetcode

//思路:
// 贪心策略
// 假设第 i 轮进行卖出操作,买入操作价格应该在 i 之前并且价格最低。
public int maxProfit(int[] prices) {
    int n = prices.length;
    if(n==0 || n==1){
        return 0;
    }
    int minValue = prices[0];
    //初始时,不进行交易,当然收益为0
    int maxProfit  = 0 ;
    for(int i=1;i<n;i++){
        minValue = Math.min(minValue,prices[i]); //在 i 轮卖出前,以最低价格买入
        maxProfit = Math.max(maxProfit,prices[i]-minValue); //贪心策略:每轮都买出
    }
    return maxProfit;
}