zoukankan      html  css  js  c++  java
  • LeetCode 152

    Maximum Product Subarray

    Find the contiguous subarray within an array (containing at least one number)
    which has the largest product.

    For example, given the array [2,3,-2,4],
    the contiguous subarray [2,3] has the largest product = 6.

     1 /*************************************************************************
     2     > File Name: LeetCode152.c
     3     > Author: Juntaran
     4     > Mail: Jacinthmail@gmail.com
     5     > Created Time: Fri 29 Apr 2016 03:46:31 PM CST
     6  ************************************************************************/
     7 
     8 /*************************************************************************
     9 Maximum Product Subarray
    10 
    11 Find the contiguous subarray within an array (containing at least one number)
    12 which has the largest product.
    13 
    14 For example, given the array [2,3,-2,4],
    15 the contiguous subarray [2,3] has the largest product = 6.
    16 ************************************************************************/
    17 
    18 #include<stdio.h>
    19 
    20 void maxAndmin( int a, int b, int c, int* max, int* min )
    21 {
    22     if( a > b )
    23     {
    24         if( a > c )
    25         {
    26             *max = a;
    27             *min = b > c ? c : b;
    28         }
    29         else
    30         {
    31             *max = c;
    32             *min = b;
    33         }
    34     }
    35     else
    36     {
    37         if( a > c )
    38         {
    39             *max = b;
    40             *min = c;
    41         }
    42         else
    43         {
    44             *max = b > c ? b : c;
    45             *min = a;
    46         }
    47     }
    48 }
    49 
    50 int maxProduct( int* nums, int numsSize )
    51 {
    52     int result = nums[0];
    53     int lastMax = nums[0];
    54     int lastMin = nums[0];
    55     int i;
    56     for( i=1; i<numsSize; i++ )
    57     {
    58         maxAndmin( nums[i], nums[i]*lastMax, nums[i]*lastMin, &lastMax, &lastMin );
    59         result = lastMax > result ? lastMax : result;
    60     }
    61     printf("result is %d
    ", result);
    62     return result;
    63 }
    64 
    65 int main()
    66 {
    67     int nums[] = {-2, 3, -4};
    68     int numsSize = 3;
    69     maxProduct( nums, numsSize );
    70     return 0;
    71 }
  • 相关阅读:
    深入了解Go Playground
    计算机程序设计艺术学习笔记1
    Docker 和一个正常的虚拟机有何区别?
    现代计算机架构常见时延(摘自计算机系统结构--量化研究方法)
    内核开发时应该注意的点
    gem5线程相关的类—SimpleThread类,ThreadState类(src/cpu/thread_state.*)
    GEM5中模拟的系统调用(部分没实现)
    字典树(trie)
    UML类图几种关系的总结
    C,C++宏中#与##的讲解
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5446787.html
Copyright © 2011-2022 走看看